Joe Essey
Joe Essey

Reputation: 3527

Rails - Display a list of associated objects attribute

I have a page that lists novels and I'd like to show a thumbnail of each of the associated illustrations. I know that the association is working because I can display the toString equivalent of each of the associated illustration objects. When I try to iterate through the list of illustrations, I get:

undefined method `image_thumbnail_url' for #<ActiveRecord::Relation:0x007f023c07aa18>

Here's the code:

<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>

<h1 style="padding-left:25px">Archive Overview</h1>

<% @novels.each do |novel| %>
<div class="row">
    <div class="span3" style="padding:0px 0px 25px 25px">
        <%= link_to novel.name, novel %>
    </div>
    <div class="span4">
        <p><%= novel.author%></p>
        <p><%= novel.publisher %></p>
        <p><%= novel.publication_date %></p>
    </div>
    <div class="span5">
        <div style="display: none;"><%= illustrations = @novels.map{ |novel| novel.illustrations} %>
        </div>
        <ul>    
            <% illustrations.each do |illustration| %>
            <li><%= illustration.image_thumbnail_url %></li>
            <% end %>
        </ul>
    </div>
</div>

Upvotes: 0

Views: 324

Answers (1)

Mischa
Mischa

Reputation: 43298

You're doing some very strange things in your code. First of all if you want to run code without displaying it you can use <% ... %> instead of <div style="display: none;"><%= ... %></div>.

The actual problem is here:

illustrations = @novels.map{ |novel| novel.illustrations }

When doing this you don't get an array with illustration objects, but an array with a collection of illustration objects. And a collection doesn't have the method image_thumbnail_url.

You are already iterating over novels, so I suggest you simply do this:

<div class="span5">
  <ul>    
  <% novel.illustrations.each do |illustration| %>
    <li><%= illustration.image_thumbnail_url %></li>
  <% end %>
  </ul>
</div>

Upvotes: 1

Related Questions