rails has_many in show只显示表名

时间:2017-10-25 00:16:24

标签: ruby-on-rails

我有以下has_many协会。

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

我希望在语句show.html.erb中调用结果。以下代码的<%= l.phases.name %>部分显示&#39; Phase&#39;,这是表名,而不是名称的值。

<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>

这是指标表的设置方式:

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

2 个答案:

答案 0 :(得分:1)

由于它有很多阶段,你应该用循环显示每个阶段的名称。

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

答案 1 :(得分:0)

您的关联不正确。由于身份has_many :phases和阶段belongs_to :identity,因此没有理由指定直通选项。然后你会做

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

检索特定Identity标识的每个阶段的名称。