Marco Bompani
Marco Bompani

Reputation: 11

Check existance with first method in Rails

I want to check if a record already exist in my database. In my function i have this code:

mailcode = params[:q]
check = User.where("custom_mailcode = 'mailcode'").first

Now i'm in trouble with the if statement. I think to do something like that:

if check == nil
  doing something
else
  doing something
end

But it doesn't work because check is never nil. How can i fix that?

Upvotes: 0

Views: 108

Answers (6)

Timo Saloranta
Timo Saloranta

Reputation: 160

I assume you want to modify or read the user if it's found. That can be accomplished like this:

mailcode = params[:q]
user = User.find_by(custom_mailcode: mailcode)
if user
  # do something with the user
else
  # backup logic
end

Or, as is often needed, you may want to create the object, if it's not already found. There's a find_or_create_by shorthand for that purpose:

mailcode = params[:q]
user = User.find_or_create_by(custom_mailcode: mailcode)
user.update(meaning_of_life: 42)

Upvotes: 0

nathanvda
nathanvda

Reputation: 50057

Ha I see the error, the error is not in your check, but in your where-clause. You are always looking for a fixed string called mailcode, not the value of the variable. The easiest fix is just to write the where differently:

check = User.where(custom_mailcode: params[:q]).first

Or use proper string interpolation

check = User.where("custom_mailcode = '#{mailcode}'").first

which you should avoid, because this makes your application vulnerable to SQL injection attacks; just showing the proper way to do string interpolation.

And then you just test

if check == nil

But I personally prefer check.nil?.

Upvotes: 0

max
max

Reputation: 102423

If you intend to use the user record you can instead use find_by

user = User.find_by(custom_mailcode: params[:q]) # User / nil
if user
  # ...
else 
  # ...
end

find_by unlike where returns the first record or nil.

If you do not plan on using the database values than use .any? it will issue a COUNT SQL query which is slightly faster and uses less memory.

# ActiveRecord only loads a boolean into memory
if User.where(custom_mailcode: params[:q]).any?
  # ...
else 
  # ...
end

Upvotes: 1

Prosenjit Saha
Prosenjit Saha

Reputation: 106

You can do the following:

if check = User.where(custom_mailcode: params[:q]).first
  p check
else
  doing something else
end   

Upvotes: 0

AJFaraday
AJFaraday

Reputation: 2450

You could try

User.where("custom_mailcode = 'mailcode'").any?

Upvotes: 1

The Whiz of Oz
The Whiz of Oz

Reputation: 7043

You could do

if check.present?
  ...
else
  ...
end

Upvotes: 0

Related Questions