2016-07-11 193 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