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