将参数传递给 Rails partial

Passing parameters to Rails partial

在我的 Rails 4.2.1 应用程序中,我有 PostsComments(嵌套在 Posts 中):

   # config/routes.rb

   resources :posts do
      resources :comments
   end

我有以下部分评论:

   # app/views/comments/_comment.html.erb

   <%= comment.body %>

我正在尝试从 Posts 视图中渲染该部分:

   # app/views/posts/show.html.erb

   <% @comments.each do |comment| %>
     <%= render 'comments/comment', :locals => { :comment => comment } %>
   <% end %>

问题是我在尝试呈现部分时遇到 未定义的局部变量或方法 "comment" 错误。

我是 Rails 的新手,但在我看来我正在将 comment 变量正确传递给部分变量。我是否漏掉了一些明显的东西?

谢谢

更新

我在文档中找错了地方。参见 http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials

要么加入partial

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

或渲染集合: 这是通过 rails 使用型号名称

完成的
<%= render @comments %>

或明确

<%= render partial: 'comments/comment', collection: @comments %>

渲染部分的 shorthand 语法不支持通过 locals 散列传递变量。在那种情况下,你可以使用这个:

<%= render 'comments/comment', :comment => comment  %>

尝试渲染局部的速记方法。这是更可取的,因为您不必指定其他选项。

 <%= render 'comments/comment', { :comment => comment } %>

阅读此 URL 以了解更多信息; http://api.rubyonrails.org/classes/ActionView/PartialRenderer.html