the_
the_

Reputation: 1173

Partial passing variable error

I have a rails 4 app that has some code like:

<% @store.products.each_with_index do |p, i| %>
   <%= render "product_fields", locals: {product:p, index: i} %>
<% end %>

and the product_fields partial looks like:

//LOTS OF HTML CODE HERE
<% if params[:action] == "edit" %>
   <%= render "edit_product_fields", locals: {p: product, i: index } %>
<% end %>

But'm getting the error (on _product_fields.html.erb):

NameError in Products#edit
undefined local variable or method `p' for #<#<Class:0x00000101e35da8>:0x00000101a86568>

What's going wrong? Also, I was wondering if there is a cleaner way of passing variables to partials within partials? I tried to do something like locals: {w:w} (so there would be consistent naming for the variables, but it didn't seem to work either.

Upvotes: 0

Views: 95

Answers (2)

mnelson
mnelson

Reputation: 3012

In rails 3+ you don't need to provide a locals option. Just pass the variables directly.

<%= render 'product_fields', product: p, index: i %>

Upvotes: 1

Sibevin Wang
Sibevin Wang

Reputation: 4558

You should add partial keyword in your render, otherwise, the locals would not work.

<%= render partial: "product_fields", locals: { product: p, index: i } %>

<%= render partial: "edit_product_fields", locals: { p: product, i: index } %>

Upvotes: 0

Related Questions