Reputation: 573
In my music review app the Pins model has attributes of Pin.artist and Pin.album. I'm trying to list each artist reviewed on the site and which albums of theirs have been reviewed. Below is what I have so far, but I want to do it without repeating the artist name.
Controller:
@pin_albums = Pin.group(:album).order('artist')
View:
<% @pin_albums.each do |pin| %>
<%= pin.artist %> |
<%= link_to pin.album, copy_pin_path(pin) %>
<br/>
<% end %>
This lists them like this:
The Beatles | Let It Be
The Beatles | Abbey Road
Bob Dylan | Blood On The Tracks
Bob Dylan | Highway 61 Revisited
I want to list them like so:
The Beatles | Let It Be
| Abbey Road
Bob Dylan | Blood On The Tracks
| Highway 61 Revisited
I need to do something to the effect of:
<% @pin_albums.each do |pin| %>
<ul>
<li><%= pin.artist %></li>
<ul>
<% pin.artist.each do |pin_album| %>
<li><%= link_to pin_album.album, pin_album %></li>
<% end %>
<br/>
<% end %>
I know that the above nested tables won't work, but that's the gist of what I'm trying to figure out.
The above nested code gives me an "Undefined method 'each'" on the pin.artist.each line.
Upvotes: 2
Views: 97
Reputation: 36860
You could store the pin.artist in a local variable and only print it when it changes.
<% last_artist = nil %>
<% @pin_albums.each do |pin| %>
<%= last_artist != pin.artist ? (last_artist = pin.artist) : '' %> |
<%= link_to pin.album, copy_pin_path(pin) %>
<br/>
<% end %>
EDIT Moved scope of local variable
Upvotes: 1
Reputation: 573
Here is what I ended up doing to accomplish this. (I put it into a table for styling purposes)
<% last_artist ||= nil %>
<table id="artist">
<tr>
<th>Artist</th>
<th></th>
<th>Album</th>
</tr>
<% @pin_albums.each do |pin| %>
<% if last_artist != pin.artist %>
<tr>
<td><%= pin.artist %></td>
<td><%= link_to image_tag(pin.image), pin %></td>
<td><%= link_to pin.album, copy_pin_path(pin) %></td>
</tr>
<% else %>
<tr>
<td></td>
<td><%= link_to image_tag(pin.image), pin %></td>
<td><%= link_to pin.album, copy_pin_path(pin) %></td>
</tr>
<% end %>
<% last_artist = pin.artist %>
<% end %>
I set the local variable last_artist ||= nil to start, based on Steve's suggestion above, and then set last_artist = pin.artist at the end of each loop.
Upvotes: 0