0

I have a common problem that normally I would solve with locals, but this time wont work.

I have the following block:

        <% @user.followers.each do |follower| %>
            <%= render "follower_card" %>
        <% end %>

And the following partial:

<div class="row follower-card">
    <%= image_tag follower.avatar_url(:smallthumb), class: "col-4 inline avatar_medium circle" %>
    <ul class="col-8 inline">
        <li><%= follower.name %></li>
        <li><%= follower.location %></li>
        <li class="lightgray small inline"><span class="bold"><%= follower.photos.count %></span> Spots</li> - 
        <li class="lightgray small inline"><span class="bold"><%= follower.albums.count %></span> Spotbooks</li>
    </ul>
</div>

I'm getting the following error:

undefined local variable or method `follower' for #<#<Class:0x007fe791a4c8d0>:0x007fe799b14b98>
Gibson
  • 2,055
  • 2
  • 23
  • 48

3 Answers3

4

This should work (specifying the follower variable):

<%= render "follower_card", follower: follower %>

Anyway, I recommend you to use collection rendering for performance reasons. Take a look here: http://guides.rubyonrails.org/layouts_and_rendering.html. Should be something like:

<%= render "follower_card", collection: @user.followers %>

Related question: Render partial :collection => @array specify variable name

Note

Old syntax to pass variables to partials is also valid (verbose, but less elegant IMHO):

<%= render partial: "follower_card", locals: { follower: follower } %>
Community
  • 1
  • 1
markets
  • 6,709
  • 1
  • 38
  • 48
2

This is because you are not passing the variable to the partial. The scope of the partial is limited to itself, and you are not making follower available inside. You will have to use:

    <% @user.followers.each do |follower| %>
        <%= render "follower_card", locals: {follower: follower} %>
    <% end %>

Is the proper way.

Jorge de los Santos
  • 4,583
  • 1
  • 17
  • 35
1
<%= render "follower_card", follower: follower %>

or

<%= render partial: "follower_card", locals: {follower: follower} %>
Jiří Pospíšil
  • 14,296
  • 2
  • 41
  • 52