Adam Kolkman
Adam Kolkman

Reputation: 132

Efficient way to check for existence of object and set equal to in Rails

In Rails 4, I want to set a variable equal to an ActiveRecord object but only if it exists. For instance, I want to set the instance variable @admin equal to the admin with a given password I have passed in through params. This is how I am doing it now:

if Admin.find_by_email(params[:email])
   @admin = Admin.find_by_email(params[:email])
end

I need to check the existence of an admin with an email 'params[:email]' to handle my edge case where an invalid email is passed in. However, this approach requires me doing 2 database requests. I would prefer to do only one and accomplish the same thing. Any suggestions?

Upvotes: 1

Views: 566

Answers (2)

MrYoshiji
MrYoshiji

Reputation: 54882

You can simply do:

@admin = Admin.find_by_email(params[:email])

And @admin will be equal to nil if no Admin is found

OR use a temp variable:

admin_tmp = Admin.find_by_email(params[:email])
@admin    = admin_tmp if admin_tmp.present?

Upvotes: 1

j-dexx
j-dexx

Reputation: 10406

Just remove the if statement. Dynamic finders like find_by_email will return nil if they don't find anything.

Then when code depends on an admin exists

unless @admin.blank?
  #do stuff
end

Upvotes: 3

Related Questions