模型的关联返回名称,而不是模型的名称属性

Association returning name of the Model, instead of model's name attribute

我的代码是运行:

<% @organization.events.each do |event| %>
<p>
    <table>
        <tr>
            <td>
                <%= event.name %>
            </td>
            <td>
                <%= event.vips.name %>
            </td>
        </tr>
    </table>
</p>
<% end %>

我的联想:

class Event < ActiveRecord::Base
  belongs_to :organization
  has_many :vips
end

class Vip < ActiveRecord::Base
    belongs_to :organization
    belongs_to :event
end

class Organization < ActiveRecord::Base
    belongs_to :user
    has_many :events
    has_many :vips
end

我的活动 table 有一个 vip_id 列,该列会在填写新活动表单时填充。

我遇到的问题是 "event.vips.name" 在呈现视图时显示为 "Vip"。

但是,与该特定事件关联的 vip 具有名称属性 "John"

我是否遗漏了有关如何正确调用 vip 对象的内容?

问题是 event.vips returns Vip 个对象的集合。

如果您想显示所有 VIP 的名字,例如用逗号分隔,您可以将 event.vips.name 更改为 event.vips.map(&:name).join(', ')

或者如果你只想显示第一个 VIP 的名字,你可以这样做 event.vips.first.name

更新

event.vips.pluck(:name).to_sentence 将是一个更优雅的解决方案(感谢@Simone Carletti 的建议)。