开发者

Setting a :has_many :through association on a belongs_to association Ruby on Rails

开发者 https://www.devze.com 2023-01-18 15:53 出处:网络
I have three models, each having the following associations: class Model1 < ActiveRecord::Base has_many :model2s

I have three models, each having the following associations:

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 a开发者_如何学编程round this?
end

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

As you can see in the commented text, I have mentioned what I need.


You just create the method to access it

class Model2 < ActiveRecord::Base
  belongs_to :model1

  def model3s
    model1.model3s
  end
end

Or, you can delegate to model1 the model3s method

class Model2 < ActiveRecord::Base
  belongs_to :model1

  delegate :model3s, :to => :model1

end


Why not try:

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

This will have active record join model2 and model3 by model1_id leaving model1 completely out of it and should be more efficient.

0

精彩评论

暂无评论...
验证码 换一张
取 消