[英]Setting a :has_many :through association on a belongs_to association Ruby on Rails
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 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
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 或者,您可以将model3s方法委托给model1
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. 这将通过model1_id具有活动记录联接model2和model3,而将model1完全排除在模型之外,并且应该更有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.