Reputation: 2356
post = Post.find 666
ActiveRecord::RecordNotFound: Couldn't find Post with 'id'=666
post => nil
post = "Banana"
post = Post.find 666
ActiveRecord::RecordNotFound: Couldn't find Post with 'id'=666
post => "Banana"
I want to make sure post
is nil
if the find doesn't return anything. Is there an elegant way of assigning nil if it comes up empty handed?
Upvotes: 1
Views: 62
Reputation: 8777
If you insist on using find
, you need to rescue
the ActiveRecord::RecordNotFound
exception. However, this is very slow, and hardly Rails idiomatic, so I suggest you use find_by
as suggested in the answer above.
begin
post = Post.find(666)
rescue ActiveRecord::RecordNotFound
post = "Banana"
end
Upvotes: 1