Rails: how do you access belongs_to fields in a view?
activerecord, ruby-on-rails
Solution
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
Problem
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 ```