Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11915

Rails 4 render partial with locals

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?

Upvotes: 2

Views: 2368

Answers (2)

Kenny Chan
Kenny Chan

Reputation: 1232

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.

Upvotes: 3

Khanh Pham
Khanh Pham

Reputation: 2973

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

Upvotes: -1

Related Questions