Ashbury
Ashbury

Reputation: 2356

Assign a value if RecordNotFound

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

Answers (2)

Drenmi
Drenmi

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

B Seven
B Seven

Reputation: 45941

This is how to do it:

post = Post.find_by(id: 666)

Upvotes: 4

Related Questions