3

我正在使用ancestrygem 来创建嵌套评论。

在相关的 Railscasts 情节中,他使用了一个辅助方法,该方法使用了很多content_tag's... 但我的部分非常复杂,我不想那样做(我希望它嵌入到 ruby​​ 中)。

问题是当局部变量被递归渲染时,局部变量没有被传递。

注释的初始呈现(递归开始的地方):

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

这会创建嵌套对象的哈希。从那里,部分应该接管:

<% 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 %>

但是,当我运行它时,我会undefined local variable or method 'comments'引用上面部分的第 1 行。这只发生在递归的第二个循环中(我假设除此之外),初始循环工作正常。

我知道变量是正确的,因为在渲染调用之前你会看到我放了<!-- binding.pry -->. 如果我在那里使用 pry,我可以看到它comments确实具有正确的值。

我不确定在这里做什么...谢谢!

4

1 回答 1

3

要么做:

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

或者:

<%= render('shared/comments', comments: child_comments) if child_comments %>
于 2013-12-01T21:11:16.160 回答