[RAILS] Undefined local variable or method error in partial template collection option

Purpose of the article

Since I am a beginner, I would appreciate it if you could point out any mistakes. Posted for memorandum and output purposes.

If you are not familiar with partial templates, this article is easy to understand. https://pikawaka.com/rails/partial_template#collection%E3%82%AA%E3%83%97%E3%82%B7%E3%83%A7%E3%83%B3

Error with collection option

The code that causes the error.

show.html.slim (file calling the partial template)


= render partial: 'reviews/user_review', collection: @reviews

From my point of view, I expect that each element of @reviews will be assigned to the review of the following partial template destination. However, I get an error that review is undefined as shown below. The value has not passed.

ActionView::Template::Error (undefined local variable or method `review' for #<#<Class:0x00007fe1e3474948>:0x00007fe1df516738> Did you mean? @reviews): 

_user_review.slim(Partial template)


= "#{review.purpose}"

Change the variable of the partial destination (Solution ①)

Upon examination, it says that the local variable will be the one specified by: partial. In this case, it is necessary to define user_review, not review, in the partial template. This is displayed safely.

show.html.slim (partial template)


= "#{user_review.purpose}"

Specify the variable in the view file to be partially called (Solution 2)

As mentioned in solution (1), it is assumed that the local variable is specified by: partial, but if you want to use the local variable with a different name, use the as option. In this case, if you want to set the variable used in the partial template destination as the initially set review, specify review with the as option in the caller's view file as shown below. This is displayed safely.

show.html.slim (partial template)


= render partial: 'reviews/user_review', collection: @reviews, as: "review"

Summary

In the first way of writing, the one with the same name as the partial template is defined as a variable in the view file. If you want to use a variable that is not the name of the partial template in the partial template, specify it with the as option.

Recommended Posts

Undefined local variable or method error in partial template collection option
When using Slim in Ruby on Rails, "undefined local variable or method` f'for "is displayed in form_with
I get an error with bundle install and puma cannot be installed.
Undefined local variable or method error in partial template collection option
Be absolutely careful when putting the result of and / or in a variable!
I got an error "undefined method` create'" in RSpec
rspec Error: ActionView :: Template :: Error: undefined method `name'for nil: NilClass
[Ruby] undefined method `dark?'occurs in rqr_code