Determine if ActiveRecord Object is New

Ruby on-RailsActiverecord

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

#new_record? does just that:

object.new_record?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjrhicksView Question on Stackoverflow
Solution 1 - Ruby on-RailsDamienView Answer on Stackoverflow
Solution 2 - Ruby on-RailsJohn BeynonView Answer on Stackoverflow