【发布时间】:2010-09-06 16:20:05
【问题描述】:
我为模型类别和产品(均使用脚手架创建)创建了一个连接表。产品型号是这样的:
class Product < ActiveRecord::Base
belongs_to :category
def category_id
category.id if category
end
def category_id=(id)
self.category = Category.find_by_id(id) unless id.blank?
end
end
类别模型是这样的:
class Category < ActiveRecord::Base
has_and_belongs_to_many :products
end
在 form.html.erb 中,我创建了一个包含所有类的 Dropbox,供用户选择:
<p>
<label for="product_category_id">Category:</label><br />
<%= f.collection_select :category_id, Category.find(:all), :id, :name, :prompt => "Select a Category" %>
</p>
然而,当我看产品展示时:
<p>
<b>Category:</b>
<%= @product.category_id %>
</p>
或产品列表(index.html.erb):
<td><%= product.category_id %></td>
没有类别。只是空白。我不明白。 category_id 方法或关联有问题吗?
【问题讨论】:
标签: ruby-on-rails