Check the return value of “save”, otherwise use “save!”

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

And for production you can use https://github.com/fnando/notifier to send `UnCaught` exception notifications

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s