【发布时间】:2011-10-06 12:55:33
【问题描述】:
我有两个模型,带有“belongs_to”的“product”和带有“has_many”的“category”。产品有一个外键“category_id”。在 product/_form 表单中,我试图在类别字段中包含一个选择选项,该选项显示类别表中的选项。但是当我单击提交时,category_id 不会填充到产品表中。请帮忙...
product_controller.rb
def create
@product = Product.new(params[:product])
respond_to do |format|
if @product.save
format.html { redirect_to([:backend, @product], :notice => 'Product was successfully created.') }
format.xml { render :xml => @product, :status => :created, :location => @product }
else
format.html { render :action => "new" }
format.xml { render :xml => @product.errors, :status => :unprocessable_entity }
end
end
end
_form.html.erb
<%= f.label :category %><br />
<%= f.select :category_id, options_from_collection_for_select(Category.all, :id, :name), :prompt => "Select" %>
models/product.rb
class Product < ActiveRecord::Base
attr_accessible :name, :desc, :price, :is_special
belongs_to :category
end
models/category.rb
class Category < ActiveRecord::Base
attr_accessible :name
has_many :products
end
【问题讨论】:
标签: ruby-on-rails-3 model associations nested-forms