在belongs_to关联上设置 :has_many :through 关联 Ruby on Rails
我有三个模型,每个模型都有以下关联:
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
正如您在评论文本中看到的,我已经提到了我需要的东西。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需创建访问它的方法
或者,您可以将 model3s 方法委托给 model1
You just create the method to access it
Or, you can delegate to model1 the model3s method
为什么不尝试:
这将使活动记录通过 model1_id 连接 model2 和 model3,而将 model1 完全排除在外,并且应该更高效。
Why not try:
This will have active record join model2 and model3 by model1_id leaving model1 completely out of it and should be more efficient.