【问题标题】:Passing parameters to Rails partial将参数传递给 Rails 部分
【发布时间】:2015-06-29 15:09:36
【问题描述】:

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

【问题讨论】:

  • # app/views/comments/_form.html.erb 是不是打错字了?
  • 是的...对不起,修正了错字。

标签: ruby-on-rails ruby partials


【解决方案1】:

要么添加partial

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

或者渲染集合: 这是通过使用模型名称的 rails 来实现的

<%= render @comments %>

或明确

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-02
        • 2011-08-10
        • 1970-01-01
        • 1970-01-01
        • 2012-08-28
        • 2013-01-16
        相关资源
        最近更新 更多