2
votes

Rails beginner here. I want to display a list of all products belonging to a specific category. I wanted to keep it simple, so each product has only one category. When I show the category, the products are there, but they appear in an array, like this:

Name: Soldering

Category ID: 2

Products: [#< Product id: 5, title: "Hacksaw", description: "Finetooth Hacksaw", image_url: >>"hacksaw.jpg", price: #, created_at: "2012-07-14 >>22:34:07", updated_at: "2012-07-17 22:18:14", category_id: 2, category_name: nil>, #< Product id:8, >>title: "Torch", description: "Welding Torch", image_url: "torch.jpg", price: >>#, created_at: "2012-07-15 08:40:05", >>updated_at: "2012-07-15 08:40:05", category_id: 2, category_name: nil>]

This is the categories/show.html.erb:

<p>
  <b>Products:</b>
  <%= @category.products %></p>
</p>

And the categories controller:

def show
  @category = Category.find(params[:id])

  respond_to do |format|
    format.html # show.html.erb
    format.json { render json: @category }
  end
end

What I want to do is just display a list of the products names, but when I try this in the show.html.erb:

<p>
    <b>Products:</b>
    <%= @category.product.name %></p>
</p>

...I get the following error:

undefined method `product' for #< Category:0x007ff03cd59e98>

I can't figure out what's wrong.

2

2 Answers

4
votes

You need to iterate through your @category.products. @category.products will give you all the Product models that belong to @category.

@category (the Category, which has a collection of Products) will not respond to product - it doesn't know what that is. All it knows is it has a bunch of Products.

<% @category.products.each do |product| %>
    <p>
        <b>Product:</b>
        <%= product.name %>
    </p>
<% end %>
0
votes

This is something similar I have been working on. It might help comparing.

show.html.erb

     <p>
      <b>Title:</b>
      <%= @product.title %>
    </p>

    <p>
      <b>Description:</b>
      <%= @product.description %>
    </p>

    <p>
      <b>Image url:</b>
      <%= @product.image_url %>
    </p>

    <p>
      <b>Price:</b>
      <%= @product.price %>
    </p>

controller

  def show
    @product = Product.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @product }
    end
  end