Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 319
David Jones Avatar asked Nov 21 '12 14:11

David Jones


People also ask

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is Belongs_to in Ruby on Rails?

2.1 The belongs_to AssociationA belongs_to association sets up a connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


2 Answers

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
like image 118
gabrielhilal Avatar answered Sep 21 '22 02:09

gabrielhilal


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 
like image 37
Thanh Avatar answered Sep 19 '22 02:09

Thanh