简体   繁体   中英

rails has_many in show just displays table name

I have the following has_many association.

class Indicator < ApplicationRecord
  belongs_to :statement, required: false
  belongs_to :identity, required: false
  belongs_to :phase, required: false
end

class Statement < ApplicationRecord
  belongs_to :student, required: false
  has_many :indicators   
  has_many :identities, through: :indicators 
  accepts_nested_attributes_for :identities
end

class Identity < ApplicationRecord
  has_many :indicators   
  has_many :statements, through: :indicators 
  accepts_nested_attributes_for :statements
  has_many :phases
end

class Phase < ApplicationRecord
  has_many :indicators
  belongs_to :identity, required: false
end

I'm looking to call the results in the statement show.html.erb. The <%= l.phases.name %> portion of the below code displays 'Phase', which is the table name and not the value of name.

<table>
 <th>Description</th>
 <th>Phase</th>
 <% @statement.identities.each do |l| %>
   <tr>
    <td><%= l.description %></td>
    <td><%= l.phases.name %></td>
   </tr>
  <% end %>
</table>

This is how the indicator table is setup:

| id | statement_id | identity_id | phase_id |
| 1  |      2       |      1      |    3     |
| 2  |      2       |      2      |    2     |
| 3  |      3       |      1      |    1     |
| 4  |      3       |      2      |    1     |

Since it has many phases you should display the name of each phase with a loop.

<% l.phases.each do |p| %>
<%= p.name %>
<% end %>

Your associations are incorrect. Since Identity has_many :phases and Phase belongs_to :identity , there is no reason to specify a through option. You would then do

<% @statement.identities.each do |l| %>
   <tr>
    <td><%= l.description %></td>
    <td><%= l.phases.pluck(:name) %></td>
   </tr>
  <% end %>

to retrieve the name of each of the phases for a particular instance of Identity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM