Ruby-on-rails 确定 ActiveRecord 对象是否为新对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7842920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:12:41  来源:igfitidea点击:

Determine if ActiveRecord Object is New

ruby-on-railsactiverecord

提问by jrhicks

How can I check if an ActiveRecordobject is new or is already persisted?

如何检查ActiveRecord对象是新对象还是已经持久化?

回答by Damien

An ActiveRecord object lifecycle:

ActiveRecord 对象生命周期:

1.new record

1.新纪录

item = Item.new
item.new_record? #=> true

2.persisted

2.坚持

item.save
item.persisted? #=> true

3.changed

3.改变了

item.name = "other"
item.changed? #=> true

4.destroyed

4.毁坏

item.destroy
item.destroyed? #=> true

回答by John Beynon

#new_record?does just that:

#new_record?就是这样:

object.new_record?