Home » Ruby » How to know whether a model is new or not?

How to know whether a model is new or not?

Posted by: admin November 30, 2017 Leave a comment

Questions:
class Post < ActiveRecord::Base
end

post = Post.new

How do I judge whether the ‘post’ is a new model which is not pulled from the database?

Answers:
post.new_record?

Questions:
Answers:

ActiveRecord’s new_record? method returns true if the object hasn’t been saved yet.

Questions:
Answers:

you can use post.persisted? as well, if it return false means record in new

persisted?