确定ActiveRecord对象是否为New

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

97399 次浏览

#new_record?就是这样做的:

object.new_record?

一个ActiveRecord对象生命周期:

1. __abc0

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

2. __abc0

item.save
item.persisted? #=> true

3. __abc0

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

4. __abc0

item.destroy
item.destroyed? #=> true