Rails 4 局部渲染

Rails 4 render partial with locals

我有部分 _errors.html.haml 来显示我的应用程序中的表单错误。部分里面的代码:

.errors
  %ul
    - errors.full_messages.each do |message|
      %li= message

我正在将 projects/new.html.haml 的部分渲染为

= render 'shared/errors', locals: { errors: @project.errors } if @project.errors.any?

部分错误位于 views/shared 目录中。

但是当我尝试呈现部分错误时出现错误。

undefined local variable or method errors' for #<#<Class:0x0055895405bbc0> :0x00558951a80fe0>

如果我把渲染线改成

= render 'shared/errors', errors: @project.errors if @project.errors.any?

有效。为什么在这种情况下使用 locals 不起作用?

我猜你的问题是为locals创造条件。

您可以尝试这样做:

- if @project.errors.any?
  = render partial: 'shared/errors', locals: { errors: @project.errors }

_errors.html.haml

.errors
  %ul
    - test_errors.full_messages.each do |message|
      %li= message

只是补充 Khanh 的回答。我已经尝试了所有的变化。看来,如果您想使用术语 locals 进行 Rails 部分渲染,则需要指定关键字 partial

显式 所以这行得通

= render partial: 'shared/errors', locals: { errors: @project.errors } if @project.errors.any?

隐式 或者简写为

= render 'shared/errors', errors: @project.errors if @project.errors.any?

所以总而言之,如果您指定用于渲染部分的散列键,则必须显式指定其所有键。否则你将不必指定散列键并让 rails 根据位置隐式计算。