Fork me on GitHub

Check the return value of "save", otherwise use "save!"

02 Nov 2012

Richard Huang (flyerhzm@gmail.com)

Before

If you use "save" on an invalid record, it will not be saved:

post = Posts.new do |p|
  p.title = "example"
  p.body = "An example"
end
post.save

This code may work at the moment, but it is fragile. If a later refactoring introduces a new required column to Posts, then the save call will silently start failing.

Refactor

If you think the record can never be invalid, or don't want to check the return value, use "save!"

post = Posts.new do |p|
  p.title = "example"
  p.body = "An example"
end
post.save!

Now you will get an error if the post cannot be saved, which will alert you to the problem.

Similar methods

The record.update_attributes method will also return "false" if it failed to save changes. Just as for save, you should check the return value or use update_attributes!.

The RecordClass.create method may fail to save the newly created method, but will not return false in that case. It should be avoided for this reason, and you should always use RecordClass.create!.

Tags