2

I have a partial _errors.html.hamlto display the form errors in my application. The code inside the partial:

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

I am rendering the partial from projects/new.html.haml as

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

The errors partial resides in views/shared directory.

But I get an error when I try to render the errors partial.

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

If I change the rendering line to

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

it works. Why doesn't using locals work in this case?

Arun Kumar Mohan
  • 11,517
  • 3
  • 23
  • 44
  • I answered [a question](http://stackoverflow.com/questions/38129112/rails-undefined-local-variable-or-method-page/38142541#38142541) has same problem. You can check the source of [render](https://github.com/rails/rails/blob/8cb8ce98d903929342e2ca3a54a07ab5196baf93/actionview/lib/action_view/helpers/rendering_helper.rb#L26) to see why it does not work. – Thanh Jul 12 '16 at 06:59

2 Answers2

3

Just to add on Khanh's answer. I have experimented all the variation. It seems that if you would like to use the term locals for Rails partial rendering, you would need to specify the keyword partial.

Explicit So this would work

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

Implicit Or the short form would be

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

So in conclusion, if you specify the hash key for rendering partial, all its key has to be specified explicitly. Else you would have to not specify the hash key and let rails figure out implicitly based on the position.

Kenny Chan
  • 1,232
  • 1
  • 15
  • 20
-1

I guess that your problem is making condition for locals.

You can try to do this:

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

In _errors.html.haml

.errors
  %ul
    - test_errors.full_messages.each do |message|
      %li= message
Khanh Pham
  • 2,848
  • 2
  • 28
  • 36