Tyler DeWitt
Tyler DeWitt

Reputation: 23576

Check if Rails Database Query Returns Nothing

I'd like to know if a Rails database query returns a row or not (I don't need to know whats in the row, just if a row is returned).

I can do this:

academic_year = AcademicYear.find_by_raw_input(year)

if academic_year 
 ...
end

but if I mistype and do a find_all_by:

academic_year = AcademicYear.find_all_by_raw_input(year)

then an empty array is returned, which causes the if statement to be true.

I know, I should be careful and just avoid the all call, but is there a rails-esque call to see if the return result from any query (all or not) is nil?

Upvotes: 2

Views: 1818

Answers (1)

deefour
deefour

Reputation: 35360

As you said, find_by_... will return nil, and find_all_by_... will return []. I think what you're looking for is .blank?.

if !academic_year.blank?
  #...
end

In console

> AcademicYear.find_by_raw_input(some_non_existent_year).blank?
  => true
> AcademicYear.find_all_by_raw_input(some_non_existent_year).blank?
  => true

Upvotes: 4

Related Questions