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
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.
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? 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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With