繁体   English   中英

show中的rails has_many仅显示表名称

[英]rails has_many in show just displays table name

我有以下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 %>部分显示“ Phase”,这是表名而不是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>

指标表的设置方法如下:

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

由于它具有多个阶段,因此应使用循环显示每个阶段的名称。

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

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

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

检索特定Identity实例的每个阶段的名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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