0

I want to iterate through an array of objects

<% @users.each do |user| %>
  <%= render "member_list" %>
<% end %>

My question is how do I pass the user object to the partial, and how do I reference it in the partial. I know how to do it if it's just a single object, but I don't know how to pass the single object from the array to it.

I tried passing user to it and reference user in the partial, but it doesn't recognize user in the partial.

Jhorra
  • 6,233
  • 21
  • 69
  • 123

2 Answers2

1
<% for user in @users %>
  <%= render "member_list" , locals => {:user => user}%>
<% end %>

in partial:

Hello. I'm <%= user.name %>
brayne
  • 1,355
  • 2
  • 16
  • 27
1

You might do it without loop - pass it as a :collection parameter. To use a custom local variable name within the partial, specify the :as option in the call to the partial:

<%= render :partial => "member_list", :collection => @users, :as => :member %>

With this change, you can access an instance of the @users collection as the member local variable within the partial.

Bohdan
  • 8,298
  • 6
  • 41
  • 51