You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在index视图中展示双层嵌套关联的属性值?

Fixing Photographer Display in Your Djob Index Table

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 Rig model, you declared has_one :photographer (singular), but tried using accepts_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 Djob model, you can remove accepts_nested_attributes_for :photographers entirely. 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 joins query was excluding djobs/rigs without photographers (since inner joins require all joined tables to have matching records)
  • You weren't preloading the photographer association, 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 with Djob.includes(rigs: :photographer).first.photographers can help confirm if the association is pulling data correctly.

内容的提问来源于stack exchange,提问作者Ethanph892

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:45:18