views:

20

answers:

0

The question is at the bottom, but the code describes the bulk of it :)

Here's the base of the code, shortened to get to the core of it:

ActiveRecord::Base.class_eval do
  def self.joins(*others)
    has_many :parent_join_models, :as => :child
    has_many :child_join_models, :as => :parent

    options = others.extract_options!
    through = (options[:as] || :parent).to_s + "_join_models"

    others.each do |other|
      has_many other, :through => through.to_sym
    end
  end
end

class Group < ActiveRecord::Base
  joins :images, :class_name => "Image", :as => :parent
  joins :photos, :class_name => "Image", :as => :parent
end

class SubGroup < ActiveRecord::Base
  joins :pictures, :class_name => "Image", :as => :parent
end

class Image < ActiveRecord::Base

end

class JoinModel
  belongs_to :parent, :polymorphic => true
  belongs_to :child, :polymorphic => true
end

And this is what happens when you use it:

group     = Group.create!
subgroup  = SubGroup.create!
image     = Image.create!

group.images << image
puts JoinModel.all
  #=> [#<JoinModel id: 1, parent_id: 1, parent_type: "Group", child_id: 1, child_type: "Image">]
JoinModel.destroy_all

subgroup.images << image
puts JoinModel.all
  #=> [#<JoinModel id: 2, parent_id: 1, parent_type: "Group", child_id: 1, child_type: "Image">]

My question is, how do I make it so when I create that join model from the subclass it's associated with, via subgroup.images << image, that it will say parent_type: "SubGroup" rather than Group? I've never been able to figure this one out.

Update

If I change this one line in ActiveRecord core, it works perfectly:

module ActiveRecord
  module Associations
    class HasManyThroughAssociation < HasManyAssociation
      protected
      def construct_owner_attributes(reflection)
        if as = reflection.options[:as]
          { "#{as}_id" => @owner.id,
            # CHANGE 'class.base_class' to 'class'
            "#{as}_type" => @owner.class.base_class.name.to_s }
        else
          { reflection.primary_key_name => @owner.id }
        end
      end
    end
  end
end

... is this a bug?