I'm a Ruby on Rails / jQuery web developer. Follow me at @sikachu

Possible pitfall on ActiveRecord::Base#create

August 21st, 2010 Posted in Ruby, Ruby on Rails

I 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

Well, what do you think would be the result of the following expression?

if Post.create(:title => nil)
  puts "Saved!"
  puts "Validation error ..."

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!"
  puts "Validation error ..."

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
  • A.

    Either the validates_presence_of is accepting nil and is only checking for Blanks or the validation is ignored at all 🙂
    What do you think?


  • You could also use Post.create!(:title => nil) and either let the exception bubble out or rescue from it.

  • Yeah, but that would defeat the purpose of this blog post. I just try to point out that #create return `self` 🙂