1

質問は一番下にありますが、コードはその大部分を説明しています:)

コードのベースは次のとおりです。コードのコアに到達するために短縮されています。

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コアでこの1行を変更すると、完全に機能します。

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

...これはバグですか?

4

0 に答える 0