问题
The best way I've found to search for things where I specifically don't want character-case to matter is:
@tag = Rails.env.development? ? Category.where("LOWER(name) LIKE ?", "%#{params[:find]}%")[0] : Category.where("LOWER(name) ILIKE ?", "%#{params[:find]}%")[0]
I have to have the .env
finder because I use Heroku, and I haven't cared to get PostgreSQL setup on my dev machines. Still, isn't there something like:
@tag = Category.find_by_name(params[:find], case_sensitive: false)
Are there options that we can pass to the find_by
helper in Rails? This would be a nice one.
回答1:
Yes, Rails supports case-insensitive queries via the built-in Arel library or a gem such as Squeel.
回答2:
Are there options that we can pass to the find_by helper in Rails? This would be a nice one...
No there isn't. (see the API)
Yes, that would be a nice one.
You will probably not accept this answer because your question wasn't really a question
Which is probably why you got downvoted.
Maybe you could also lowercase the params[:find]
(params[:find].downcase
) and care to get PG setup on your dev machines.
Category.where("LOWER(name) LIKE ?", "%#{params[:find].downcase}%").first
In the meantime, you could extract the query in your model:
category.rb
def self.search_by_name(name)
if Rails.env.development?
where("LOWER(name) LIKE ?", "%#{name.downcase}%").take
else
where("LOWER(name) ILIKE ?", "%#{name}%").take
end
end
controller
@tag = Category.search_by_name(params[:find])
来源:https://stackoverflow.com/questions/19303637/case-insensitive-search-in-rails