Ossie
Ossie

Reputation: 1113

How to show data from associated model in a view?

Still stuck on https://stackoverflow.com/questions/19156673/create-in-multiple-models-with-one-form-in-a-has-many-through-association but now trying a different tack. I just want the associated models to SHOW correctly.

I should mention this is a has_many through relationship. Miniatures have many Manufacturers through Production.

This is what my Miniature display is trying to show. Three objects from it's own model and one from the Manufacturers model.

 <%= @miniature.name %><br />
   Material: <%= @miniature.material %><br />   
   Manufacturer: <%= @miniature.manufacturers.select(:name).to_a %><br />
   Release date: <%= @miniature.release_date.strftime("%d %b %Y") unless @miniature.release_date.blank? %><br />
   <%= link_to "Edit this miniature listing", edit_miniature_path %>

what it shows is

Miniature 1 
Material: China 
Manufacturer: [#<Manufacturer id: nil, name: "Cytt">, #<Manufacturer id: nil, name: "Yenn">] 
Release date: 02 Mar 2002 Edit this miniature listing

How can I rephrase <%= @miniature.manufacturers.select(:name).to_a %>so that it returns only the two names and not all the crap around them?

At least it proves that my associations are working, even if I can't get them to create through nested forms.

Upvotes: 1

Views: 425

Answers (1)

spickermann
spickermann

Reputation: 107142

<%= @miniature.manufacturers.map(&:name).join(', ') %>

or

<% @miniature.manufacturers.each do |manufacturer| %>
  <%= manufacturer.name %>
  ...
<% end %>

Upvotes: 6

Related Questions