我有2个型号,如下所述。我想这样做,以便当用户创建产品时,他们必须从类别表中存在的类别中进行选择。
表:
产品:id,name
类别:id,name
categories_products:category_id,product_id
class Product
has_and_belongs_to_many :categories
accepts_nested_attributes_for :categories
end
class Category
has_and_belongs_to_many :products
end
class ProductsController < ApplicationController
def new
@product = Product.new
@product.categories.build
end
def create
@product = Product.new(params[:product])
if @product.save
redirect_to @product, :notice => "Successfully created product."
else
render :action => 'new'
end
end
end
视图/产品/ new.haml
= form_for @product do |f|
= f.text_field :name
= f.fields_for :categories do |cat_form|
= cat_form.collection_select :id, Category.all, :id, :name, :prompt => true
然而,这失败并给了我: 对于ID =
的产品,找不到ID = 3的类别我希望能够在创建时将现有类别分配给产品。有一个简单的方法吗?
答案 0 :(得分:1)
如果您实际从表单中更新accepts_nested_attributes_for
,则只需使用categories
即可。如果你所做的只是选择一个类别来添加你的新产品,你可以简化这样的一切:
class Product
belongs_to :category
end
class Category
has_many :products
end
class ProductsController < ApplicationController
def new
@product = Product.new
end
def create
@product = Product.new(params[:product])
if @product.save
redirect_to @product, :notice => "Successfully created product."
else
render :action => 'new'
end
end
end
如果您只是将产品分配到一个类别,则不需要它们之间的多对多关系。
至于观点:
= form_for @product do |f|
= f.text_field :name
= f.collection_select :category_id, Category.all, :id, :name, :prompt => true