9

私には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

コメント文でわかるように、私は必要なものについて述べました。

4

2 に答える 2

12

アクセスするメソッドを作成するだけです

class Model2 < ActiveRecord::Base
  belongs_to :model1

  def model3s
    model1.model3s
  end
end

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

class Model2 < ActiveRecord::Base
  belongs_to :model1

  delegate :model3s, :to => :model1

end
于 2010-10-05T13:42:06.043 に答える
0

試してみませんか:

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 によって model2 と model3 にアクティブなレコードが結合され、model1 が完全に除外され、より効率的になります。

于 2012-05-03T21:34:27.370 に答える