How to know whether a model is new or not?

Ruby on-RailsRubyModel

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

post.new_record?

Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

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

http://apidock.com/rails/ActiveRecord/Persistence/persisted%3F"> persisted?

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
QuestionCroplioView Question on Stackoverflow
Solution 1 - Ruby on-RailsFaisalView Answer on Stackoverflow
Solution 2 - Ruby on-RailsJohn TopleyView Answer on Stackoverflow
Solution 3 - Ruby on-RailsThorinView Answer on Stackoverflow