Use save(false), not save_without_validation

Written . 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>> 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).