问题
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