Home > Mobile >  How to get current object on partial colection
How to get current object on partial colection

Time:08-20

I have the following partial:

<%= render partial: "shared/cards",
                collection: @products,
                as: :product,
                ga_event_category: 'Redirect #{product.name}'
%>

How can I get the product name in this case? Because I'm using collection I can't have access to the object on every dynamic iteration?

CodePudding user response:

Rails makes the instance object available inside the partial using the name of the partial (without the underscore) as the instance variable.

When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial.

Read this: https://guides.rubyonrails.org/layouts_and_rendering.html#using-partials

In your case, I'd rename the partial as product.

render partial: "shared/product", collection: @products

Inside that partial you can set the value of ga_event_category using the product instance from the collection.

If you don't change the name of the partial, the collection instance would be cards.

CodePudding user response:

You mean like this:

<% @products.each do |product| %>
  <%= render partial: "shared/cards",
             product: product,
             ga_event_category: "Redirect #{product.name}"
  %>
<% end %>
  • Related