加入Model + STI + Polymorphic Associations - ActiveRecord可以不这样做吗?

时间:2010-09-11 07:58:13

标签: ruby polymorphic-associations single-table-inheritance

问题在底部,但代码描述了它的大部分内容:)

这是代码的基础,缩短为了它的核心:

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

这就是你使用它时会发生的事情:

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">]

我的问题是,当我通过subgroup.images << image与其关联的子类创建该联接模型时,我会如何做到这一点,它会说parent_type: "SubGroup"而不是Group?我从来没能弄明白这一点。

更新

如果我在ActiveRecord核心中改变这一行,它可以完美地运行:

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

......这是一个错误吗?

0 个答案:

没有答案