我有两个型号,'产品'带'belongs_to','category'带'has_many'。产品有一个外键'category_id'。在product / _form形式中,我试图包含带有select选项的category字段,该选项显示类别表中的选项。但是当我点击提交时,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" %>
模型/ product.rb
class Product < ActiveRecord::Base
attr_accessible :name, :desc, :price, :is_special
belongs_to :category
end
模型/ category.rb
class Category < ActiveRecord::Base
attr_accessible :name
has_many :products
end
答案 0 :(得分:1)
attr_accessible :name, :desc, :price, :is_special
负责此
您应该将:category_id
添加到此列表中。
当您使用attr_accessbible时,所有其他字段都受到保护