Search code examples
ruby-on-railsassociationshas-manybelongs-to

Cannot save associated model id in Rails


I have set up models Producer and Product. When I want to create a new product, in the form I can choose Producers from list. Here is the code:

<%= select("producer", "producer_id", Producer.all.collect {|t| [ t.name, t.id ] }, {:prompt => 'Select producer'})%>  

It works fine, but when I want to save the created product, it shows up that producer_id cannot be blank, which is caused by the validations I created. I have set column producer_id to Product table, created associations, everything what I was told.

Here is my code:

Product Controller

def new
@product = Product.new

respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @product }
end 

def create
   @product = Product.new(params[:product])
end

Product model

belongs_to :producer

Producer model

has_many :products

I hope somebody can help!


Solution

  • The problem is that in your controller you reference params[:product], but in your view you use "producer". Change select("producer".. to select("product" and it will work fine.

    def create
       @product = Product.new(params[:product])
    end
    
    <%= select("producer", "producer_id", Producer.all.collect {|t| [ t.name, t.id ] }, {:prompt => 'Select producer'})%>