Question

I'm using the ancestry gem to create nested comments.

In the related Railscasts episode, he uses a helper method which uses a lot of content_tag's... but my partial is quite complex and I don't want to do it that way (I want it in embedded ruby).

The problem is that when a partial is being rendered recursively, the local variables are not being passed.

Initial rendering of comments (where the recursion starts):

def index
  @comments = @commentable.comments.includes(:user).arrange(order: :created_at)
  render partial: 'shared/comments', locals: { comments: @comments }
end

That creates a hash of nested objects. From there, the partial should take over:

<% comments.each do |comment, child_comments| %>
  <div class="comment" data-id="<%= comment.id %>">
    <%= image_tag comment.user.avatar_url, class: 'avatar', size: '40x40' %>
    <div class="content">
        <%= simple_format h(comment.body) %>
      <!-- binding.pry -->
      <%= render('shared/comments', locals: { comments: child_comments }) if child_comments %>
    </div>
  </div>
<% end %>

However, when I run this I get undefined local variable or method 'comments' referencing line 1 of the partial above. This only happens on the recursive 2nd loop though (and I assume any beyond that), the initial loop works fine.

I know the variables are correct because immediately before the render call you will see I put <!-- binding.pry -->. If I use pry there I can see that comments do indeed have the proper values.

I'm not sure what to do here... thanks!

Was it helpful?

Solution

Either do:

<%= render( partial: 'shared/comments', locals: { comments: child_comments }) if child_comments %>

Or:

<%= render('shared/comments', comments: child_comments) if child_comments %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top