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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 02:12:37

问题


The code I'm running:

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

My associations:

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

My events table has a vip_id column that is populated when the new event form is filled out.

The problem I'm having is that "event.vips.name" displays as "Vip" when the view is rendered.

However, the vip associated with that specific event has the name attribute "John"

Am I missing something on how to call the vip object correctly?


回答1:


The problem is that event.vips returns a collection of Vip objects.

If you want to display all of the VIP's names separated by commas for instance, you could change event.vips.name to event.vips.map(&:name).join(', ').

Or if you want to just display the first VIP's name, you could do event.vips.first.name.

UPDATE

event.vips.pluck(:name).to_sentence would be a more elegant solution (thanks @Simone Carletti for the suggestion).



来源:https://stackoverflow.com/questions/32188041/association-returning-name-of-the-model-instead-of-models-name-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!