Determine if ActiveRecord Object is New

前端 未结 2 1855
既然无缘
既然无缘 2020-12-07 08:56

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

相关标签:
2条回答
  • 2020-12-07 09:49

    An ActiveRecord object lifecycle:

    1.new record

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

    2.persisted

    item.save
    item.persisted? #=> true
    

    3.changed

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

    4.destroyed

    item.destroy
    item.destroyed? #=> true
    
    0 讨论(0)
  • 2020-12-07 10:00

    #new_record? does just that:

    object.new_record?
    
    0 讨论(0)
提交回复
热议问题