My syntax is off. I want to create a scope by_name
that finds all agencies
whose name attribute contains the passed in string (case insensitive).
Here is what I have:
class Agency < ActiveRecord::Base
scope :by_name, ->(agency_name) { where('name ILIKE ?', "%#{agency_name}%") }
end
In the rails console I type in agencies = Agency.by_name("foo")
. Here is the query generated:
SELECT `agencies`.* FROM `agencies` WHERE (name ILIKE '%foo%')
Here is the error message:
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ILIKE '%foo%')
It is in PostgreSQL the keyword ILIKE can be used instead of LIKE to make the match case-insensitive according to the active locale. This is not in the SQL standard but is a PostgreSQL extension. In MySQL you do not have ILIKE.
select * from users where lower(first_name) = 'ajay'; The method is to make the field you are searching as uppercase or lowercase then also make the search string uppercase or lowercase as per the SQL function.
Mysql ignores case for its LIKE comparisons.
I think it should be:
scope :by_name, lambda { |agency_name|
where('name LIKE ?', "%#{agency_name}%") # not ILIKE
}
It is in PostgreSQL the keyword ILIKE can be used instead of LIKE to make the match case-insensitive according to the active locale. This is not in the SQL standard but is a PostgreSQL extension.
In MySQL you do not have ILIKE. Checkout MySQL docs on string comparison functions.
Bonus - you can also use Arel. Take a look:
scope :by_name, lambda { |agency_name|
where(Agency.arel_table[:name].matches("%#{agency_name}%"))
}
Why yes, because there's no such thing as ILIKE
in MySQL. Only LIKE
. You may have seen ILIKE
as a case-insensitive version of LIKE
in PostgreSQL, but your current RDBMS is different.
Your best bet is using LOWER
on both sides to achieve mostly equivalent effect:
.where('LOWER(name) LIKE LOWER(?)', "%#{agency_name}%")
Credit to @mu is too short for his answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With