Ethanph892
Ethanph892

Reputation: 57

How to list nested attribute values on 'index' view?

I have a table named "djobs". This table has a nested table named "rigs" that is connected through the column 'djob_id'. Each djob has_many rigs associated with it. The issue is, I have a table of information being displayed on the djob index view. In this table, I want to display each djob, and within each djob, display each rig name associated with that particular job. I can' figure out how to only display the rig names for that particular djob. It always displays every rig name in every djob.

I've tried various solutions found online, but they all result in each djob displaying every single rig name and not just the rigs associated with that particular djob. For example, for job 1, it should display rigs "A", "B", "C". But instead, it displays every rig name that has ever been associated to a djob.

controller djobs:

def index_photography
  @djobs = Djob.all.order(:id).includes(:rigs)
  @djob_id = @djobs.map(&:id)
  @djob_rigs = Rig.where(:djob_id => @djob_id)
end

model djobs:

class Djob < ActiveRecord::Base
  has_many :rigs
  accepts_nested_attributes_for :rigs, allow_destroy: true
end

model rigs:

class Rig < ActiveRecord::Base
  belongs_to :djob
end

view:

<tbody>
  <% @djobs.each do |djob| %>
    <tr>

      <td class="dotted" ><%= djob.jobtype %></td>

      <td class="dotted" >
        <% @djob_rigs.each do |rig| %>
          <%= rig.name %>
        <% end %>
      </td>

     </tr>
  <% end %>
</tbody>

I expect a view with a table that has two columns: jobtype and rigs. Where each row lists the one jobtype and all of the rig names associated with that djob. Instead I get the jobtype and every rig names ever associated to a djob.

Upvotes: 1

Views: 104

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

Try using joins instead includes. It'll get any rig associated with a djob:

def index_photography
  @djobs = Djob.order(:id).joins(:rigs)
end

<tbody>
  <% @djobs.each do |djob| %>
    <tr>
      <td class="dotted">
        <%= djob.jobtype %>
      </td>

      <td class="dotted" >
        <% djob.rigs.each do |rig| %>
          <%= rig.name %>
        <% end %>
      </td>
     </tr>
  <% end %>
</tbody>

The .all isn't necessary. You can try also selecting the needed columns from both tables:

Djob.order(:id).joins(:rigs).select(:jobtype, 'rigs.name')

Upvotes: 1

Related Questions