Rails:如何在视图中访问belongs_to字段?

6
在下面给出的MVC结构中,我应该如何访问:category? 我将其添加到attr_accessible列表中并重新启动了服务器,但调用p.category仍然没有返回任何内容。 我相信你们的Rails专家会知道发生了什么。先谢谢! 模型:
class Product < ActiveRecord::Base
  belongs_to :category
  belongs_to :frame
  belongs_to :style
  belongs_to :lenses
  attr_accessible :description, :price
end

视图

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

控制器

def sunglass
  @product = Product.all
end

p.category 返回一个 Category 对象,如果产品没有关联的类别,则返回 nil。您可以尝试 <%= p.category.inspect %> 来显示类别(如果存在)。 - MrYoshiji
啊,好的。所以我尝试了 p.category.inspect,确实一切都是 nil。但是我刚刚在 dbconsole 中手动建立了这些关联。我想知道为什么它们没有显示出来。 - David Jones
您可以在控制台中将类别设置为产品,如下所示:Product.where(:id => 5).first.update_attributes(:category => Category.where(:id => 3).first) - MrYoshiji
你的 Category 里面有 "has_many" 吗? - fengd
不需要,只需 attr_accessible :name - David Jones
你的对象 product 是否有关联的类别? - MrYoshiji
2个回答

6
您需要指定要显示的categories表的哪一列。例如,一个名为name的列:
<% @product.each do |p| %>
 <%= p.category.name %>
<% end %>

否则它将返回对象... 换句话说,所有列 { id: 1,name:'blabla'等 } 另外,
class Category < ActiveRecord::Base
   has_many :products
end

2
这是定义:

belongs_to :category

为了让每个产品模型对象都有一个指向类别表的参考点,只需定义一个引用点。例如,您的类别模型具有名称、类型等列。

一个产品属于一个类别,而一个类别有多个产品。现在,如何找到产品所属类别的名称?您不能像这样编写代码:

product.category # this is just reference to Category table

你应该像这样写:
product.category.name # this will get category's name which product belongs to

如果您想获取类别的类型(例如):
product.category.type 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接