如果RecordNotFound分配值

时间:2015-04-23 16:50:53

标签: ruby-on-rails ruby

post = Post.find 666

ActiveRecord::RecordNotFound: Couldn't find Post with 'id'=666

post =>零

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

post => "香蕉"

如果查找不返回任何内容,我想确保postnil。如果它空手而归是否有一种优雅的方式来分配nil?

2 个答案:

答案 0 :(得分:4)

这是怎么做的:

post = Post.find_by(id: 666)

答案 1 :(得分:1)

如果您坚持使用find,则需要rescue ActiveRecord::RecordNotFound例外。但是,这非常缓慢,并且几乎没有Rails惯用,因此我建议您使用上面答案中建议的find_by

begin
  post = Post.find(666)
rescue ActiveRecord::RecordNotFound
  post = "Banana"
end