How to assign values using fields_for with a has_many association in rails 3 -
i have 2 models described below. make when user creates product, have select categories exist in categories table.
tables:
products: id, name
categories: 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
views/products/new.haml
= form_for @product |f| = f.text_field :name = f.fields_for :categories |cat_form| = cat_form.collection_select :id, category.all, :id, :name, :prompt => true
however, fails , gives me: couldn't find category id=3 product id=
i able assign existing category product on creation. there easy way this?
you need use accepts_nested_attributes_for
if you're updating categories
form. if you're doing choosing single category add new product to, can simplify this:
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
if you're assigning product 1 category, don't need many-to-many relationship between them.
as view:
= form_for @product |f| = f.text_field :name = f.collection_select :category_id, category.all, :id, :name, :prompt => true
Comments
Post a Comment