David Jones
David Jones

Reputation: 10219

Rails: how do you access belongs_to fields in a view?

Given the MVC structure below, how can I access :category? I added it to the list of attr_accessible and restarted the server, but calling p.category still doesn't return anything. I'm sure you Rails experts will know what's going on. Thanks in advance!

Model

class Product < ActiveRecord::Base
  belongs_to :category
  belongs_to :frame
  belongs_to :style
  belongs_to :lenses
  attr_accessible :description, :price
end

View

<% @product.each do |p| %>
<%= p.category %>
<% end %>

Controller

def sunglass
  @product = Product.all
end

Upvotes: 6

Views: 13285

Answers (2)

Thanh
Thanh

Reputation: 8604

This definition:

belongs_to :category

just define a reference point to table Category for every object of Product model. Example your Category model has some column like: name, type,...

One product belongs to one category, and Category has many products. Now, how do you find category's name of a product? You can not write like this:

product.category # this is just reference to Category table

You should write like this:

product.category.name # this will get category's name which product belongs to

If you want to get type of category (example):

product.category.type 

Upvotes: 2

gabrielhilal
gabrielhilal

Reputation: 10769

You need to specify which column of categories table you want to display. For example, a column called name:

<% @product.each do |p| %>
 <%= p.category.name %>
<% end %>

Otherwise it will return the object... in other words, all the columns {id: 1, name: 'blabla', etc }

Also,

class Category < ActiveRecord::Base
   has_many :products
end

Upvotes: 6

Related Questions