1

How do I do the following in one line?

<% song.albums.each do |album| %>
  <%= link_to album.title, album %><br />
<% end %>

I've tried two approaches that haven't worked.

This gives me the entire array:

<%= song.albums.each {|album| link_to album.title, album } %>

And this output is blank:

<% song.albums.each {|album| link_to album.title, album } %>
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Brett
  • 2,775
  • 4
  • 27
  • 32

1 Answers1

2
<%= song.albums.map{ |a| link_to(a.title,a) }.join("<br/>").html_safe %>

If you really need/want the extra <br/> after the last item, then either put it after this block, or use:

<%= song.albums.map{ |a| "#{link_to(a.title,a)}<br/>" }.join.html_safe %>

Note that using an explicit <br/> in your HTML is usually "code smell"; you should probably be using CSS display:block on the anchor or on a wrapping element like <li> instead.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • I had to wrap this in raw() to get the html output. But it works great. Thanks so much. – Brett May 15 '12 at 17:20
  • 1
    @Brett See my edit; you can also [use `html_safe`](http://stackoverflow.com/questions/4251284/raw-vs-html-safe-vs-h-to-unescape-html) to achieve your needs. I prefer this over `raw` as the intent is more obvious. – Phrogz May 15 '12 at 17:23
  • Very good. As for the
    , I'm saving all the CSS formatting for the end of the project. I agree that it's tacky for now. Thanks again.
    – Brett May 15 '12 at 17:28