Question: In Rails 5, how do I prevent find_by from returning a result if none exists?

Question

In Rails 5, how do I prevent find_by from returning a result if none exists?

Answers 3
Added at 2017-09-06 23:09
Tags
Question

I"m using Rails 5. I'm confused about looking up a record by its ID. I have a model, User, but when I look up with a nil id, I get back a result ...

2.4.0 :002 > User.find_by(nil)
  User Load (0.5ms)  SELECT  "users".* FROM "users" LIMIT $1  [["LIMIT", 1]]
 => #<User id: 2, provider: "google_oauth2", uid: "10152354902902839283465", email: "user@hotmail.com", first_name: "Dave", last_name: "LastName", oauth_token: nil, oauth_expires: nil, created_at: "2017-08-28 19:49:18", updated_at: "2017-09-04 20:03:36", last_login: nil, currency_id: nil, email_confirmed: false, confirm_email_key: nil, confirm_key_expires: nil>

How do I look up an active record by its ID but have it return nil if no ID matches the given parameter?

Answers to

In Rails 5, how do I prevent find_by from returning a result if none exists?

nr: #1 dodano: 2017-09-06 23:09

One way to do it would be to utilize BEGIN and RESCUE.

begin
  User.find(id)
rescue ActiveRecord::RecordNotFound
  p "Display error here"
end

One-liner:

User.where(id: 'id').present? ? User.find('id') : nil
nr: #2 dodano: 2017-09-07 00:09

Here's a one-line solution:

User.where(id: id).first

This assumes your id column is not nullable (which is usually the case). If not you can do:

User.where(id: id).where.not(id: nil).first
nr: #3 dodano: 2017-09-07 00:09

The parameters you are passing to find_by define the condition to apply to the query -- find_by(*args) is just where(*args).take.

The code you show, User.find_by(nil), is the same as passing in no condition, so is equivalent to User.where(nil).take, or User.take, resulting in a query equivalent to select * from users limit 1.

If you want to search by id and not have an error thrown when you pass nil or a value that doesn't exist, use:

User.find_by(id: id)

If you want an error to be thrown if the id doesn't exist then use:

User.find(id)
Source Show
◀ Wstecz