Sometimes I see the ! after a save, and a few other active record methods... what is the difference?
save
will return false if the record can't be saved (validation errors for instance).
save!
will raise an exception if the record can't be saved. Use save!
when you are pretty dang sure it should save with no problem, and if it doesn't then its a pretty huge bug and an exception is appropriate.
The general pattern or convention of using ! at the end of a method in rails indicates the function could raise an exception, versus the non-bang method simply returning a value.
The consequence of not throwing an exception allows you to use the return value as part of normal handling.
if obj.save # yay, it worked! else # boo end
Note this isn't a rule enforced by Ruby, simply a convention. Other libraries such as the standard library for String, has methods that return the result of the operation versus modifying the value of the object in place.
String s="Hello, world" s.gsub("world", "Joe") # returns a new string object, leaving s alone s.gsub!("world", "Joe") # modifies the value of s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With