Peter S. wrote:
Hi all,
I just begun with RoR and going through the Agile development w Rails
depot example ATM. I did everything according to the book (i believe),
and after 3 hours of googling, reading docs, making sure i did
everything correctly i can not make the validate_presence_of() to work -
at least not as it looks in the book. My Product model looks like:
class Product < ActiveRecord::Base
validates_presence_of :title
end
however, if i leave the title field empty, and push create, the newly
created product is added to the list of products without any error
message. What’s wrong?
thanks,
Peter
Peter,
I tested validates_presense_of with this model:
class Magazine < ActiveRecord::Base
validates_presence_of :title
end
Here’s my console output:
newmag = Magazine.create()
=> #<Magazine:0xb7196904 @attributes={“title”=>nil}, @new_record=true,
@errors=#
<ActiveRecord::Errors:0xb717ba8c @base=#<Magazine:0xb7196904 …>,
@errors={“tit
le”=>[“can’t be blank”]}>>
newmag = Magazine.create(:title => ‘’)
=> #<Magazine:0xb7175470 @attributes={“title”=>""}, @new_record=true,
@errors=#<
ActiveRecord::Errors:0xb7174ae8 @base=#<Magazine:0xb7175470 …>,
@errors={“titl
e”=>[“can’t be blank”]}>>
newmag = Magazine.create(:title => ’ ')
=> #<Magazine:0xb7171780 @attributes={“title”=>" "}, @new_record=true,
@errors=#
<ActiveRecord::Errors:0xb7170e0c @base=#<Magazine:0xb7171780 …>,
@errors={“tit
le”=>[“can’t be blank”]}>>
I tried leaving :title as nil, as the empty string, as well as a string
with a single space character. All three times the “can’t be blank”
error is returned, and I confirmed that the magazines table does not get
populated with a new record.
I’m running Rails 1.1.2. The Agile Web D. with Rails Book was
written to target V1.0, IIRC, but 1.0 wasn’t available when the book
went to press, so the API descriptions target 1.0, and the code examples
were tested against 0.13. I followed the depot example using 1.0
without issue.
There must be something else wrong, but I don’t know what to suggest in
trying to find it. Doesn’t the description field also have a
validates_presence_of method? You could also try running the console
and do:
product = Product.new()
product.image_url = …
product.price = …
product.description = …
product.save
to see if the save fails that way.
I hope you find the problem.