Wednesday, May 18, 2022

[FIXED] How to use a file of different name while using render @collection in Rails?

Issue

Rails saves us an each loop by letting us directly pass the collection variables to render method like following:

<%= render @products %>

By default, it will look for a file named _product.html.erb, and render it for each single item in @products collection. For somehow, the file has been named as _custom_product.html.erb, now how to tell render method to render a file of name other than the standard _product.html.erb?


Solution

You can go either way:

To access your products via product local variable in the partial:

<%= render partial: "custom_product", collection: @products, as: :product %>

Or via custom_product in the partial:

<%= render partial: "custom_product", collection: @products %>


Answered By - Maxim Filippov
Answer Checked By - David Goodson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.