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
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}"
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}"
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"
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