2016-07-11 140 views
3

我有一个部分_errors.html.haml在我的应用程序中显示表单错误。部分中的代码:Rails 4渲染部分本地人

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

我从渲染项目/ 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

+0

我回答了[一个问题](http://stackoverflow.com/questions/38129112/rails-undefined-local-variable-or-method-page/38142541#38142541)也有同样的问题。你可以查看[render]的来源(https://github.com/rails/rails/blob/8cb8ce98d903929342e2ca3a54a07ab5196baf93/actionview/lib/action_view/helpers/rendering_helper.rb#L26),看看它为什么不起作用。 – Thanh

回答

2

只是对庆的答案补充。我已经尝试了所有的变化。看起来,如果您想为Rails部分呈现使用术语locals,则需要指定关键字partial

明确所以这会工作

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

或者短期形式是

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

所以在最后,如果你指定渲染部分的哈希键,其所有密钥必须明确指定。否则,你将不得不指定散列键,并让栏根据位置隐式地找出。

0

我想你的问题是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