Ryan B
Ryan B

Reputation: 166

Rails Render Partial Inside a One Line Block

I've got a feed of information that I want to simplify by using some partials. Basically, I want to do something along the lines of

<%= 2.times { |j| render 'item_expanded', item: @social_json_feed[i + j], index: (i + j) } %>

However, the above code does not render the partial. Instead, it returns the value "2" two times. If I write the block as a do-end block it works as one would expect.

<% 2.times do |j| %>
  <%= render 'item_expanded', item: @social_json_feed[i + j], index: (i + j) %>
<% end %>

Produces the partial in the way I want. But if the do-end block works correctly a one-line block should be able to work correctly as well, right? Is it simply something about how the one-line block is formatted or is it something deeper into Rails magic? Also, why does the first example of code return "2" twice??

Upvotes: 1

Views: 828

Answers (2)

Jay Mitchell
Jay Mitchell

Reputation: 1240

If you add a call to map you should be able to keep it all on one line.

<%= 2.times.map { |j| render 'item_expanded', item: @social_json_feed[i + j], index: (i + j) } %>

Upvotes: 1

Marek Lipka
Marek Lipka

Reputation: 51151

It's because in first case it renders only return value of 2.times method call, which is 2. You should simply use the second notation.

Upvotes: 2

Related Questions