質問

私には3つのモデルがあり、それぞれに次の関連があります。

class Model1 < ActiveRecord::Base
  has_many :model2s
  has_many :model3s
end

class Model2 < ActiveRecord::Base
  belongs_to :model1
  has_many :model3s, :through => :model1  # will this work? is there any way around this?
end

class Model3 < ActiveRecord::Base
  belongs_to :model1
  has_many :model2s, :through => :model1  # will this work? is there any way around this?
end

コメントされたテキストでわかるように、私は必要なものについて言及しました。

役に立ちましたか?

解決

アクセスする方法を作成するだけです

class Model2 < ActiveRecord::Base
  belongs_to :model1

  def model3s
    model1.model3s
  end
end

または、model1 model3sメソッドをmodel1に委任することができます

class Model2 < ActiveRecord::Base
  belongs_to :model1

  delegate :model3s, :to => :model1

end

他のヒント

試してみませんか:

class Model1 < ActiveRecord::Base
  has_many :model2s
  has_many :model3s
end

class Model2 < ActiveRecord::Base
 belongs_to :model1
 has_many   :model3s, :primary_key => :model1_id,
                      :foreign_key => :model1_id

end

class Model3 < ActiveRecord::Base
  belongs_to :model1
  has_many   :model2s, :primary_key => :model1_id,  
                       :foreign_key => :model1_id
end

これにより、Model1_idがモデル1を完全に除外することにより、アクティブレコードJoin Model2とModel3がより効率的になります。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top