As a reminder,
update will return false if a validation error occurs and
update! will raise instead. The way it’s normally used is as follow:
Usage to Avoid
On the other hand, here is something to avoid:
If this action succeeds, it’s all good. However if it fails and not save the record, it will do it silently and could cause some disastrous side effects down the line. Silent failures are the worst kind of failures as it makes debugging a nightmare since the problem could be anywhere in the code.
Of course there are situations where it is acceptable. For instance you have a corrupted database and only want to update the valid records in a script… then yes, under these circumstances you don’t really care that the invalid record is not updated. However I would argue that this is quite an implicit behaviour and your code won’t express your intent unless you add comments, so why not spend the extra couple of minutes to graciously handle it?
Finally, even if there are some cases where this wouldn’t cause major issues, there is still an overwhelming number of situations where you’ll want to know that something didn’t happen as expected.
How To Fix
This is why you should either raise using
update! or react when the persistence method returns
false, like this:
Using a Linter
Rails/SaveBang: Enabled: true
Since you scrolled this far, you might be interested in some other things I wrote:
- Add Text Over an Image with Ruby
- Regression Testing For Data
- Expressing Intent Without Comments In Ruby
- The Difference Between to_s & to_str In Ruby
- Understanding Rails' Forgery Protection Strategies
- First Impressions: Rails 5 on Google App Engine
- Automatically Run RSpec on Multiple Projects
- Startup & Tech Book Reviews