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 = Product.new
@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’ %>
4:
5:
Category
6: <%= collection_select( :product, :category_id, @categories, :id,
:name ) %>
7:
.
.
.
Request
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.
Bye