Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive partial local variables are not working

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!

like image 797
Tallboy Avatar asked Jul 31 '26 11:07

Tallboy


1 Answers

Either do:

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

Or:

<%= render('shared/comments', comments: child_comments) if child_comments %>
like image 166
apneadiving Avatar answered Aug 03 '26 05:08

apneadiving



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!