3

I get error in partial line #1: undefined local variable or method 'level'

Code in my view:

<div id="comments">
    <% level = 0%>
    <% @comments.each do |comment| %>
      <%=render partial: 'comments/single_comment', locals: {level: level, comment: comment} %>
    <% end %>
    <% if 0 < level %>
    <% (level).times do %>
    </div>
    <% end %>
    <% end %>
  </div>
</div> 

And partial first lines:

<% if comment.level < level %>
  <% (level - comment.level).times do %>
  </div>
  <% end %>
<% end %> 

Any idea what's wrong here?

Marcin Doliwa
  • 3,639
  • 3
  • 37
  • 62

3 Answers3

2

Looks like this code should be work(it's no so good, but it should be work) I think problem that you use your partial (comments/single_comment) elsewhere in some part of code what we didn't see without 'level local' :)

Dmitry Dedov
  • 1,106
  • 7
  • 15
1

seems like the code is right .. try to check if you have any partial view that use single_comment filename ... and also you can use collection instead doing a loop

<%= render partial: 'comments/single_comment', collections: @comments, locals: { level: level } %>
Paul Lopez
  • 11
  • 1
  • 1
  • just run `grep -r 'single_comment' .` in `views` directory and it's the only place I use it (thanks for collections tip) – Marcin Doliwa Feb 12 '13 at 21:31
0

You are passing arguments to the partial in a wrong way. update it to following.

<%=render partial: 'comments/single_comment', locals: => {:level => level, :comment => comment} %>

now you can access your objects in partials as follows

<% if locals[:level] < level %>
  <% (level - locals[:level]).times do %>
  </div>
  <% end %>
<% end %>