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

Sometimes I see! after saving and several other active recording methods ... what's the difference?

+4
source share
2 answers

General outline or use agreement! at the end of the method in rails indicates that the function can throw an exception, compared to the non-bang method, which simply returns a value.

The consequence of the exclusion of metadata allows the return value to be used as part of normal processing.

  if obj.save
   # yay, it worked!
 else
   # boo
 end

Please note that this is not a rule applied by Ruby, just a convention. Other libraries, such as the standard library for String, have methods that return the result of an operation or change the value of an 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
+3
source

save will return false if the record cannot be saved (for example, validation errors).

save! will throw an exception if the record cannot be saved. Use save! when you know pretty well that it should save without problems, and if it is not, then it will be a pretty huge mistake and exception.

+13
source

Source: https://habr.com/ru/post/1343294/


All Articles