Brett
Brett

Reputation: 2785

Block with link_to on one line

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 } %>

Upvotes: 1

Views: 1332

Answers (1)

Phrogz
Phrogz

Reputation: 303136

<%= 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.

Upvotes: 2

Related Questions