RickD RickD - 11 months ago 60
Ruby Question

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.


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


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


def categories
@categories = ProductCategory.all

Answer Source

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.