简体   繁体   English

rails 3 - widget.save和widget.save之间的区别!

[英]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将返回false(例如,验证错误)。

save! will raise an exception if the record can't be saved. 如果无法保存记录,将引发异常。 Use save! 使用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. 当你非常确定它应该保存没有问题,如果它没有那么它是一个非常大的bug和异常是适当的。

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. 在rails中的方法结束处指示函数可以引发异常,而非bang方法只返回一个值。

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. 请注意,这不是Ruby强制执行的规则,只是一种约定。 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的标准库)具有返回操作结果的方法,而不是修改对象的值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 rails中save和sneaky_save的区别 - Difference between save and sneaky_save in rails Rails 5 如何在postgres 中保存两个数据时间之间的小时和分钟差异? - Rails 5 how to save difference in hour and minutes between two datatime in postgres? save(false)和save(:validate => false)之间的区别 - Difference between save(false) and save(:validate => false) Rails - 在动作之间保存参数 - Rails - Save parameters between actions 在动作之间保存参数 - Save parameters between actions Rails 在 Rails 5 中,“model.save”和“model.errors.empty”之间是否存在功能差异? - In Rails 5, is there a functional difference between "model.save" and "model.errors.empty?"? Rails具有许多直通关系-新保存和创建之间的区别 - Rails Has Many Through Relationship - Difference Between New-Save and Create Rails:保存对象后,计算时间差并另存为整数 - Rails: Upon object save, calculate time difference and save as integer rails 回调中 after_create、after_save 和 after_commit 的区别 - Difference between after_create, after_save and after_commit in rails callbacks Ruby on Rails 回调,before_save 和:before_create 有什么区别? - Ruby on Rails Callback, what is difference between :before_save and :before_create?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM