Passing variables through multiple partials (rails

2019-09-04 13:15发布

问题:

I am trying to pass instance variables through multiple partials and having trouble. undefined local variable or method "product"

Application.html.erb"

    <%= render 'shared/footer', :product => @product %>

_footer.html.erb

<%= render 'shared/my_form', :product => product %>

_my_form.html.erb

<%= form_for( product ) %>

UPDATE:

I'm starting to think it might be that the instance variable @product is just not being set/passed for the redirect. Could the following be causing the issue? Opened different issue here:

Instance variable not set with redirect

回答1:

You have to use this syntax:

Application.html.erb"

<%= render partial: 'shared/footer', locals: {:product => @product} %>

_footer.html.erb

<%= render partial: 'shared/my_form', locals: {:product => product} %>

_my_form.html.erb

<%= form_for( product ) %>

Notice the use of partial: and locals:



回答2:

If you want to pass local variables, you should use this syntax:

 <%= render partial: 'shared/footer', locals: { product: @product } %>
 <%= render partial: 'shared/my_form', locals: { product: product } %>
 <%= form_for( product ) %>

For reference: http://guides.rubyonrails.org/layouts_and_rendering.html (3.4.4)