I'm trying to create a new product and associate a category with the
new product. The categories are loaded into a form select field. When
I try try to create a new product, I get the error:
* Category can't be blank
My form code in _form.rhtml is:
...
<p><label for="product_category">Category</label><br/>
<%= collection_select :product, :category_id,
@categories, :id, :name, :prompt => "Select a Category" %></p>
...
My product_controller.rb is:
...
def new
load_data
@product = Product.new
end
def create
@product = Product.new(params[:product])
if @product.save
flash[:notice] = 'Product was successfully created.'
redirect_to :action => 'list'
else
load_data
render :action => 'new'
end
end
...
private
def load_data
@categories = Category.find(:all)
end
...
My product.rb model is:
class Product < ActiveRecord::Base
belongs_to :categories
Also, for some reason (maybe it's the reason the above doesn't work)
is that I get this error:
undefined method `category' for #<Product:0x344b170>
when I'm trying to define: product.category.name
Why can't it see the category's name that is related to the product?
Rails save method as you are using it will only save the selected id
key from category into the category_id field in your Product table but
will not save the category name into the "category" field.
So validates_presence_of :category in your Product model will give an
error because there is no data saved into the category field.
You can check this by looking in your database table and you will see
no data in the category field but the id field has the category id.
Try your code without the validates_presence_of :category.
I am very new to Rails - a few weeks!!! so I dont have the complete
answer - I hope this piece is helpful.
I also have the same problem and must find a way of populating my
category name field as well as the id field!!