Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails find_by case insensitive

I need to find a record from 2 parameters but I need one of them to be case insensitive. The current case sensitive line is

  c = Course.find_by(subject_area: area, cat_number: cat)

But I need subject_area to be case insensitive. How would I achieve that?

like image 735
Dracossack Avatar asked Sep 14 '16 00:09

Dracossack


2 Answers

It depends on the database, and you may need to pass in db-specific SQL for that (and not use find_by). Are you using postrges? if so, this would normally work:

Course.where("LOWER(subject_area) = ? AND cat_number = ?", area.downcase, cat)

alternatively you could convert your subject_area to downcase every time you save a new one... then just use:

Course.find_by(subject_area: area.downcase, cat_number: cat)

I could be wrong, but don't currently know of any rails-native way of doing a case insensitive rails find_by

like image 180
Taryn East Avatar answered Sep 19 '22 01:09

Taryn East


An alternative can be

c = Course.find_by("LOWER(subject_area)= ? AND cat_number = ?", area.downcase, cat)
like image 39
David Barrientos Avatar answered Sep 23 '22 01:09

David Barrientos