Ruby-on-rails 如何知道一个模型是不是新的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3333424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:57:31  来源:igfitidea点击:

How to know whether a model is new or not?

ruby-on-railsrubymodel

提问by Croplio

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?

如何判断“帖子”是否是未从数据库中提取的新模型?

回答by Faisal

post.new_record?

回答by John Topley

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

如果对象尚未保存,则ActiveRecord 的new_record?方法返回true

回答by Thorin

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

你可以使用 post.persisted 吗?同样,如果它返回 false 意味着记录在新的

persisted?

坚持?