简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM