Possible pitfall on ActiveRecord::Base#create
August 21st, 2010 Posted in Ruby, Ruby on RailsI came across this a while ago when I was trying to clean up my code. Just write it down so you won’t follow me
Consider that Post having :title attribute and
class Post < ActiveRecord::Base validates_presence_of :title end
Well, what do you think would be the result of the following expression?
if Post.create(:title => nil) puts "Saved!" else puts "Validation error ..." end
Somehow, I expected "Validation error ..." message from it, but I got "Saved!" Why?
Return value of #create
You need to remember that #create method always return the object itself, which have the id as nil. This, evaluates to true and make our code fail. The solution for this problem would be using #new to create object, and then using #save:
post = Post.new(:title => nil) if post.save puts "Saved!" else puts "Validation error ..." end
For you one-liner, I think you can do this:
if post = Post.new(:title => nil) && post.save
or (as suggested by shr)
if Post.new(:title => nil).save


