67
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?

Mladen Jablanović
  • 43,461
  • 10
  • 90
  • 113
Croplio
  • 3,433
  • 6
  • 31
  • 37

3 Answers3

116
post.new_record?
Faisal
  • 19,358
  • 4
  • 30
  • 33
40

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

John Topley
  • 113,588
  • 46
  • 195
  • 237
  • 4
    new_record? is note listed in the linked documentation I believe you meant this: http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html – Jarrod Carlson Jun 23 '12 at 16:33
  • 2
    @jcarlson Look at when I posted my answer and consider that the documentation may have changed in the meantime. – John Topley Jun 23 '12 at 18:07
10

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

persisted?

Thorin
  • 2,004
  • 1
  • 19
  • 30
  • 1
    This is more straight forward, because with `new_record?` you'll need to test for `false` to know if your record has saved. Kinda backward logic in my mind, but to each their own! – Dylan Pierce Mar 29 '17 at 13:51
  • From the link provided a comment by `hosh`: "`new_record?` will not check if the record has been destroyed." So I guess this is something to take note of if you are checking for record destroyed. – CyberMew Aug 07 '18 at 08:28