Forum: Ruby on Rails Relationship breaks Validation

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
E38607fd2dd775cb8741883534292895?d=identicon&s=25 Oem Oezkir (oem)
on 2007-03-23 14:37
Heya people, this is my first post here so if I forget some relevant
info (like logs or something) please tell me. Ok to my problem:
I have a fairly simple rails app so far, a "products"-table that belongs
to categories ( a simple one-to-many realtionship). I wanted to be able
to select a category when editing/creating a product entry so I included
a drop down list into the form for selecting a category:
<%= collection_select( :product, :category_id, @categories, :id, :name )

The controller part of this:
    @product =
    @categories = Category.find(:all, :order => "name")

The model (basic validation):
  validates_presence_of :title, :price, :category_id, :description

If I enter everything correctly it works fine.
But if I leave any field blank (so whenever the validation kicks in and
finds something bad) I get following error message:

NoMethodError in Admin/products#create

Showing app/views/admin/products/new.rhtml where line #6 raised:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.inject
Extracted source (around line #6):

3:   <%= text_field 'product', 'title'  %></p>
5:   <p><label for="product_category_id">Category</label><br/>
6:   <%= collection_select( :product, :category_id, @categories, :id,
:name ) %>

Parameters: {"commit"=>"Create", "product"=>{"price"=>"", "title"=>"",
"category_id"=>"2", "description"=>""}}

It doesn't matter what field is wrong and I could even kick validation
for category_id - it still happens.
The error doesn't happen if I remove the validation but I would really
hate to disable that.
So, any help would be greatly appreciated.
This topic is locked and can not be replied to.