在下面给出的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 %>
来显示类别(如果存在)。 - MrYoshijip.category.inspect
,确实一切都是 nil。但是我刚刚在 dbconsole 中手动建立了这些关联。我想知道为什么它们没有显示出来。 - David JonesProduct.where(:id => 5).first.update_attributes(:category => Category.where(:id => 3).first)
。 - MrYoshijiattr_accessible :name
。 - David Jonesproduct
是否有关联的类别? - MrYoshiji