Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3 - difference between widget.save and widget.save!

Sometimes I see the ! after a save, and a few other active record methods... what is the difference?

like image 345
jpw Avatar asked Dec 04 '22 23:12

jpw


2 Answers

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.

like image 91
Alex Wayne Avatar answered Dec 24 '22 17:12

Alex Wayne


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
like image 38
edk750 Avatar answered Dec 24 '22 17:12

edk750