2

I've confirmed through the rails console that this record doesn't exist. However, when I run this code, 'it exists' gets printed to the console.

Is there an issue with how I'm querying the database using ruby?

        if Companyavg.where(:company => 'goog', :word => 'baa')
            puts 'it exists'
        else
            puts 'doesnt exist'
        end

3 Answers 3

3

Change:

if Companyavg.where(:company => 'goog', :word => 'baa')

to:

if Companyavg.where(:company => 'goog', :word => 'baa').exists?

This is more efficient than using present? since it can run an optimized query to return the correct result.

The initial query that you had will always be truthy since it returns an ActiveRecord::Relation (in simple terms, a lazy untriggered query).

Sign up to request clarification or add additional context in comments.

Comments

0

Try

Companyavg.where(:company => 'goog', :word => 'baa).empty?

The issue is that the where call is returning a query, but it doesn't actually run the query until it absolutely has to. So in this case you're evaluating the truth value of a non-nil, non-false object, which is therefore true according to the rules of Ruby.

1 Comment

Looks like @PinnyM's solution is probably slightly more efficient, according to this link.
0

This is because where returns an empty relation. In ruby only nil and false statements evaluate as false. For example 0 and "" (empty string) evaluate as true.

2 Comments

This isn't accurate - it returns an untriggered relation that doesn't know yet if it's empty or not.
Ruby does regular evaluations; ActiveRecord queries do lazy evaluations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.