当前位置: 动力学知识库 > 问答 > 编程问答 >

Ruby on rails if statement for relationship error

问题描述:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: