250

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

2 Answers 2

418

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
Sign up to request clarification or add additional context in comments.

1 Comment

I'd like to add item.previously_new_record? and item.previously_persisted? to the list
317

#new_record? does just that:

object.new_record?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.