问题描述:

im having an issue displaying the name per category with the following code,

Can anyone advise please?

<% if @products.category.name == "categoryname" %>

<% @products.each do | product | %>

<%= product.name %>

<% end %>

<% end %>

I get the following error:

undefined method `category' for #

网友答案:

It appears you're calling the if statement on the @products.all

@products doesn't have a .category I'd assume judging by your error.

You'll need to change the code to this for it to work...

<% @products.each do | product | %>
    <% if @products.category.name == "Name Here" %>
        <%= product.name %>
    <% end %>
<% end %>
网友答案:

I am assuming that @products is an array or AR::Relationship. You probably want/need to loop through that variable. Looks like you are trying to access a specific instance instead of the whole array.

maybe, @products.first.category.name or something like that

相关阅读:
Top