rails has_many relationship (4 models) and how to access in the view
-
23-09-2019 - |
문제
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!
해결책
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:
script/plugin install git://github.com/ianwhite/nested_has_many_through.git
Then setup your model like this:
class Transac < ActiveRecord::Base
has_many :transaction_datas
has_many :items, :through => :transaction_datas
has_many :dvd_details, :through => :items
end
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.