[英]Rails has_many through association issue
I have 3 models: 我有3种型号:
sophead
od
od_item
sophead has many ods and od has many od_items . sophead有许多ods , od有许多od_items 。
each od_item belongs to one od and each od belongs to one sophead 每个od_item属于一个od ,每个od属于一个sophead
I want to be able to return all od_items for a specific sophead like this: 我希望能够返回特定sophead的所有od_items ,如下所示:
all_od_items_for_first_sophead = Sophead.first.od_items
what is the correct association for getting all the od_item s for a sophead ? 获取sophead的所有od_item的正确关联是什么 ?
I had tried: 我尝试过:
has_many :od_items, through: :ods
but I believe that this is incorrect as it doesn't really match this diagram - in that diagram's example (with different model names), the arrow from patients to appointments would run the other direction. 但我认为这是不正确的,因为它与该图并不完全匹配-在该图的示例(具有不同的模型名称)中,从患者到约会的箭头会朝另一个方向移动。
Thanks in advance 提前致谢
Your try was correct way to do it. 您的尝试是正确的方法。 Your models must have associations like this:
您的模型必须具有以下关联:
models/sophead.rb 型号/sophead.rb
class Sophead < ApplicationRecord
has_many :ods
has_many :od_items, through: :ods
end
models/od.rb 型号/od.rb
class Od < ApplicationRecord
belongs_to :sophead
has_many :od_items
end
models/od_item.rb 型号/od_item.rb
class OdItem < ApplicationRecord
belongs_to :od
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.