0

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.

the_
  • 1,183
  • 2
  • 30
  • 61

2 Answers2

1

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

<%= render 'product_fields', product: p, index: i %>
mnelson
  • 2,992
  • 1
  • 17
  • 19
0

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 } %>
Sibevin Wang
  • 4,480
  • 3
  • 27
  • 27