Ruby on rails 如果未找到RecordNotFound,则指定一个值

Ruby on rails 如果未找到RecordNotFound,则指定一个值,ruby-on-rails,ruby,Ruby On Rails,Ruby,post=>nil post = Post.find 666 ActiveRecord::RecordNotFound: Couldn't find Post with 'id'=666 post=>“香蕉” 如果查找没有返回任何内容,我想确保post为nil。如果空手而归,是否有一种优雅的方式来指定nil?这是如何做到的: post = "Banana" post = Post.find 666 ActiveRecord::RecordNotFound: Couldn't find Pos

post=>nil

post = Post.find 666

ActiveRecord::RecordNotFound: Couldn't find Post with 'id'=666
post=>“香蕉”

如果查找没有返回任何内容,我想确保
post
nil
。如果空手而归,是否有一种优雅的方式来指定nil?

这是如何做到的:

post = "Banana"
post = Post.find 666
ActiveRecord::RecordNotFound: Couldn't find Post with 'id'=666
这是如何做到的:

post = "Banana"
post = Post.find 666
ActiveRecord::RecordNotFound: Couldn't find Post with 'id'=666

如果坚持使用
find
,则需要
rescue
处理
ActiveRecord::RecordNotFound
异常。但是,这非常慢,而且很难理解Rails的惯用用法,因此我建议您使用上面答案中建议的
find_by

post = Post.find_by(id: 666)

如果坚持使用
find
,则需要
rescue
处理
ActiveRecord::RecordNotFound
异常。但是,这非常慢,而且很难理解Rails的惯用用法,因此我建议您使用上面答案中建议的
find_by

post = Post.find_by(id: 666)

一篇文章怎么可能是“香蕉”?我在第二个代码块的第1行设置post=“Banana”。一篇文章怎么可能是“香蕉”?我在第二个代码块的第1行设置post=“Banana”。是的,如果参数为nil,这将返回第一篇文章。“如果查找结果没有返回任何内容,我想确保post为nil。”这正是它所做的。如果没有id为666的帖子,则帖子为零。@Ashbury-不确定params与该问题有何关系。如果您正在执行
find_by(id:params[:id])
,并且没有:id param,那么post将为零。哦,您是对的,我没有像常规查找方法那样指定:id!是的,如果参数为nil,这将返回第一个post。“如果find没有返回任何内容,我想确保post为nil。”这正是它所做的。如果没有id为666的帖子,则帖子为零。@Ashbury-不确定params与该问题有何关系。如果您正在执行
find_by(id:params[:id])
,并且没有:id param,那么post将为零。哦,您是对的,我没有像常规查找方法那样指定:id!