如何在index视图中展示双层嵌套关联的属性值?
Let's break down your problem step by step and fix it properly:
1. First, Fix Model Association & Nested Attributes
Your initial error "No association found for name `photographers'" came from two small mistakes in your models:
- In your
Rigmodel, you declaredhas_one :photographer(singular), but tried usingaccepts_nested_attributes_for :photographers(plural). Correct that to match the singular association:class Rig < ActiveRecord::Base belongs_to :djob has_one :photographer accepts_nested_attributes_for :photographer # Singular, matches has_one end - In your
Djobmodel, you can removeaccepts_nested_attributes_for :photographersentirely. Since your photographers are associated through rigs, you don't need direct nested attributes for them—handle photographer attributes through the rigs' nested attributes instead.
2. Fix Your Controller Query to Load Associated Data
Your original joins(:rigs, :photographers) uses an inner join, which will exclude any djobs that don't have a rig or photographer attached. Worse, it doesn't preload the associated data properly, which can lead to missing data or slow N+1 queries.
Replace it with includes to preload the nested associations (this ensures all related rigs and their photographers are loaded in one go):
def index_photography @djobs = Djob.order(:id).includes(rigs: :photographer) end
3. Update the View to Display Photographers Correctly
Since each rig has exactly one photographer, you should iterate over each rig and display its corresponding photographer directly (this also keeps your rig names and their photographers paired together, which is probably what you want):
<td class="dotted" > <% djob.rigs.each do |rig| %> <%= rig.name %> <%# Only display photographer if one exists %> <% if rig.photographer %> <br><%= rig.photographer.name %> <% end %> <% end %> </td>
Why Your Previous Fix Didn't Show Data?
The most likely reasons are:
- Your original
joinsquery was excluding djobs/rigs without photographers (since inner joins require all joined tables to have matching records) - You weren't preloading the
photographerassociation, so Rails wasn't fetching that data from the database - If you tried
djob.photographers.each, make sure your through association is working—testing in the Rails console withDjob.includes(rigs: :photographer).first.photographerscan help confirm if the association is pulling data correctly.
内容的提问来源于stack exchange,提问作者Ethanph892

