将参数传递给Rails部分

时间:2015-06-29 15:09:36

标签: ruby-on-rails ruby partials

在我的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 %>

问题是我在尝试渲染部分时遇到未定义的局部变量或方法“注释”错误。

我对Rails很新,但我觉得我正在将comment变量正确传递给部分。我错过了一些明显的东西吗?

由于

更新

我在文档中查找错误的位置。见http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials

enter image description here

3 个答案:

答案 0 :(得分:6)

添加partial

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

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

的导轨实现的
<%= render @comments %>

或明确

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

尝试使用简写方法渲染部分。这是更优选的,因为您不必指定其他选项。

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

阅读此网址以了解详情; http://api.rubyonrails.org/classes/ActionView/PartialRenderer.html