如何显示链接模型的项目

How to display items of linked model

我有 2 个模型("Offence" 和 "OffenceType"),它们的 has_many 关系由连接管理 table "lk_offence_types".

在 "Offence" 的 index.html.erb 中,我无法显示 OffenceType 项目。 (我尝试过委托,但它似乎不适用于 has_many..)

进攻模式:

class Offence < ApplicationRecord
    has_many :lk_offence_types, inverse_of: :offence, dependent: :destroy
    has_many :offence_types, through: :lk_offence_types

    #delegate :offence_type_description, to: :offence_type
end

犯罪类型模型:

class OffenceType < ApplicationRecord
    has_many :lk_offence_types
    has_many :offences, through: :lk_offence_types
end

LkOffenceType 模型:

class LkOffenceType < ApplicationRecord
  belongs_to :offence_type, inverse_of: :lk_offence_types
  belongs_to :offence, inverse_of: :lk_offence_types  
end

进攻的index.html.erb:

<% @offences.each do |offence| %>
<tr>
<td><%= offence.offence_description %></td>
<td><%= offence.offence_types.offence_type_description %></td>
<% end %>

<%= offence.offence_types.offence_type_description %> 给我一个错误。 我也尝试过: <%= offence.offence_type_description %> 和其他语法...

我错过了什么?

(我正在使用 Ruby 2.3 和 Rails 5.0.2)

谢谢

您还需要遍历 offence types。您可能需要修复样式,这只是为了让您了解缺少的内容。

<% offence.offence_types.each do |ot| %>
 <td><%= ot.offence_type_description %></td>
<% end %>