开发者

foreign key not populating in the table on create - rails 3

开发者 https://www.devze.com 2023-04-10 22:50 出处:网络
I have two models, \'product\' with \'belongs_to\' and \'category\' with \'has_many\'. Product has a foreign key \'category_id\'. And in the form product/_form I\'m trying to include category field wi

I have two models, 'product' with 'belongs_to' and 'category' with 'has_many'. Product has a foreign key 'category_id'. And in the form product/_form I'm trying to include category field with a select option which shows the options from the 开发者_Python百科category table. But when I click on submit the category_id doesn't get populated in the product table. Please help...

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


attr_accessible :name, :desc, :price, :is_special is responsible for this

you should add :category_id to this list. when you use attr_accessbible, all other field are protected

0

精彩评论

暂无评论...
验证码 换一张
取 消