Rails has_many关系(4种模式)以及如何在视图中访问
我有 4 个模型:transac、transac_data、item、dvd_details
class Transac < ActiveRecord::Base
has_many :transac_datas
has_many :items, :through => :transaction_datas
end
class TransactionData < ActiveRecord::Base
belongs_to :item
belongs_to :transaction
end
class Item < ActiveRecord::Base
has_many :transaction_datas
has_many :transacs, :through => :transaction_datas
end
class DvdDetails < ActiveRecord::Base
has_many :items
end
现在在“transac”视图中,我需要访问所有这些模型中的内容,例如:
<td><%=h transac.status %></td>
<% transac.transaction_datas.each do |td| %>
<td><%=h td.item_type %></td>
<% end %>
<% transac.items.each do |item| %>
<td><%=h item.item_type %></td>
<% end %>
但我还需要从“DvdDetails”模型访问一些信息,该模型是“最远的” “远离交易。
我意识到做这样的事情并不会真正起作用:
class Transac < ActiveRecord::Base
has_many :transac_datas
has_many :items, :through => :transaction_datas
has_many :dvd_details, :through => :items, :through => :transaction_datas
end
并在“transac”视图的索引中执行此操作
<%=h transac.dvd_details.name %>
我需要做什么才能完成此操作?
任何帮助表示赞赏! 谢谢你!
I have 4 models: transac, transac_data, item, dvd_details
class Transac < ActiveRecord::Base
has_many :transac_datas
has_many :items, :through => :transaction_datas
end
class TransactionData < ActiveRecord::Base
belongs_to :item
belongs_to :transaction
end
class Item < ActiveRecord::Base
has_many :transaction_datas
has_many :transacs, :through => :transaction_datas
end
class DvdDetails < ActiveRecord::Base
has_many :items
end
Now in the "transac" view, I need to access stuff from all these models like:
<td><%=h transac.status %></td>
<% transac.transaction_datas.each do |td| %>
<td><%=h td.item_type %></td>
<% end %>
<% transac.items.each do |item| %>
<td><%=h item.item_type %></td>
<% end %>
BUT I also need to access some info from the "DvdDetails" model which is the "furthest" away from transac.
I realized that doing something like this wouldn't really work:
class Transac < ActiveRecord::Base
has_many :transac_datas
has_many :items, :through => :transaction_datas
has_many :dvd_details, :through => :items, :through => :transaction_datas
end
and do this in the index of "transac" view
<%=h transac.dvd_details.name %>
What do I need to do to accomplish this?
Any help is appreciated!
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,使用Ian White 的nested_has_many_through 插件,您可以按照您想要的方式以菊花链方式连接has_many。只需像这样安装插件:
然后像这样设置你的模型:
这应该可以满足你的需要。
更新:这个问题最近出现了几次。我写了一篇文章, 嵌套你的has_many :通过关系,来详细解释。它甚至在 GitHub 上有一个附带的示例应用程序可供下载和使用。
Actually, with Ian White's nested_has_many_through plugin, you can daisy-chain has_many throughs the way you want. Just install the plugin like so:
Then setup your model like this:
This should do what you need.
UPDATE: This question has come up a few times recently. I wrote an article, nesting your has_many :through relationships, to explain in detail. It even has an accompanying example application on GitHub to download and play around with.