RickD
RickD

Reputation: 79

Pass in object in partial

I would like to render a partial in my application.html.erb. The partial originates from the Product folder "products/categories". When I try to insert a partial in the application.html.erb, like below, I get undefined local variable or method `categories' for #<#:0x007fcfa35c9c78>. Any help is greatly appreciated.

application.html.erb

<%= render 'products/categories', locals: { categories: categories }%>

products/_categories.html.erb

<% @categories.each do |category| %>
 <li><%= category %></li>
<% end %>

products_controller.rb

 def categories
  @categories = ProductCategory.all
 end

Upvotes: 0

Views: 1228

Answers (4)

7urkm3n
7urkm3n

Reputation: 6311

You need to add partial: if wanna pass params to partial. Also, you have miss typo in locals, make it @categories.

<%= render partial: 'products/categories', locals: { categories: @categories }%>

and loop it without @

<% categories.each do |category| %>
 <li><%= category %></li>
<% end %>

Upvotes: 0

Dan Andreasson
Dan Andreasson

Reputation: 16202

Try to follow: Never use a instance variable in a partial.

Pass variables into the partial instead. You can use the render shorthand instead of render partial, which makes it a bit easier to read.

<%= render "products/categories", categories: @categories %>

# app/views/products/categories
<% categories.each do |category| %>
 <li><%= category %></li>
<% end %>

Upvotes: 0

Navin
Navin

Reputation: 924

You are passing locale as locals: { categories: categories } as local variable and in view you calling instance variable @categories which will not get in that view. try to pass locale as locals: { categories: @categories } and in view use

<% categories.each do |category| %>

Upvotes: 0

max pleaner
max pleaner

Reputation: 26758

With your render you have

locals: { categories: categories }

which will define categories in your partial

But in that partial you are referring to @categories.

You will still have access to all instance variables in the partial even if you don't pass them as locales.

Also be aware that controller methods aren't automatically available to views.

You need to also write helper_method :categories in the controller or move the method to the helpers file.

Although it's probably not a good idea to name local variables the same as methods, so you should rename the method to get_categories or something.

Upvotes: 1

Related Questions