我为此目的创建了一个连接表。下面的代码:产品 - 分类关联。 (编辑)belongs_to,has_and_belongs_to_many?
class CreateCategoriesProductsJoin < ActiveRecord::Migration
def self.up
create_table 'categories_products', :id => false do |t|
t.column 'category_id', :integer
t.column 'product_id', :integer
end
end
def self.down
drop_table 'categories_products'
end
end
产品型号:
class Product < ActiveRecord::Base
has_and_belongs_to_many :categories
attr_accessor :new_category_name
before_save :create_category_from_name
def create_category_from_name
create_category(:name => new_category_name) unless new_category_name.blank?
end
end
和类别型号:
class Category < ActiveRecord::Base
has_and_belongs_to_many :products
end
到目前为止好。问题在于form.html.erb。 代码在这里:
<p>
<label for="product_category_id">Category:</label><br />
<%= f.collection_select :category_id, Category.find(:all), :id, :name, :prompt => "Select a Category" %>
or create one:
<%= f.text_field :new_category_name %>
</p>
我尝试加载类别的选择框,但我得到一个消息“未定义的方法`CATEGORY_ID”为#”。
我不明白为什么?我也尝试过has_many:通过但发生了同样的事情。
我应该能够以这种方式绘制类别,因为它们是关联的,但我不是。有任何想法吗?
我试过从railscast.com的screancast,但没有运气。你有没有想到一个完整的教程/产品类别,子类别关联的例子?我还没有找到一个下降(除了railscast,但不适合我)。
非常感谢您的时间,并感谢您花时间回复的麻烦(如果您确实如此)。
编辑:我发现它是在产品模型中的问题。这里是修复:
class Product < ActiveRecord::Base
belongs_to :category
def category_name
category.name if category
end
def category_name=(name)
self.category = Category.find_by_name(name) unless name.blank?
end
end
编辑2:我也有类别的另一个问题。
类别名称未出现在视图中。我称之为category_name函数,但我没有得到任何回报。像这样(show.html.erb):
<p>
<label for="product_category_id">Category:</label><br />
<%= f.collection_select :category_name, Category.find(:all), :id, :name, :prompt => "Select a Category" %>
or create one:
<%= f.text_field :new_category_name %>
</p>
或(show.html.erb):
<td><%= product.category_name %></td>
我试图改变has_and_belongs_to_many :categories
至少我回来了 “分类” 为这个名字很奇怪......因为我有4个类别。
A产品只属于一个类别。 PS:再一次,谢谢你的时间。
不说也不行。 – storedope 2010-09-05 21:52:09