Search code examples
ruby-on-railsrubyrenderpartial

Creating a partial that can take a collection


I'm having a problem with a partial that displays takes in a collection of @users, and then creates a report like:

_users.html.erb:

<table>
<tr>
...
</tr>
<% @items.each do |u| %>
..
<% end %>
</table>

So now in my home#index erb page, I want to display 2 reports like:

But I am getting an error saying that items doesn't exist.

undefined method `each' for nil:NilClass

How do I tell the partial that @good_users or @bad_users is to be assigned to @items?


Solution

  • Use a local variable, like 'users'

    <table>
    <tr>
    ...
    </tr>
    <% users.each do |u| %>
    ..
    <% end %>
    </table>
    

    And when you're rendering the partial, set the local variable:

    render partial: 'users', locals: { users: @good_users }
    

    or

    render partial: 'users', locals: { users: @bad_users }
    

    as appropriate.