Written November 24, 2008. Tagged Ruby, Ruby on Rails.
In Active Record, I've preferred save_without_validation
to save(false)
because I like self-documenting code.
Until it was pointed out to me today, I somehow hadn't realized save_without_validation
is a method introduced by alias_method_chain
.
This means, of course, that by using save_without_validation
directly, you miss out on other parts of the save
method chain. At the time of writing, I think this is just dirty object handling. Plugins may introduce more.
For that reason, I will be using save(false)
in future. It's common enough that I can accept the lack of clarity; you could also do save(validate=false)
, of course, at the cost of an extra instance variable.
Example of how things can go wrong with save_without_validation
:
>> u = User.first
>> u.changed?
=> false
>> u.name = "foo"
=> "foo"
>> u.save
=> true
>> u.changed?
=> false
>> u.name = "bar"
"bar"
>> u.save_without_validation
=> true
>> u.changed?
=> true
>> u.name = "baz"
=> "baz"
>> u.save(false)
=> true
>> u.changed?
=> false
Note that u.changed?
is true
when using save_without_validation
, but not with save
or save(false)
.