Case insensitive active record query in rails-4

橙三吉。 提交于 2019-12-13 05:41:03

问题


Currently I am working on a project in rails 4 in which I have a user-page at example.com/username but it only finds the record if i use username in proper case, how can I perform case insensitive search in active record rails. Check out my code below

@user = User.find_by_username(params[:username].downcase)

回答1:


you will have to use something similar to where("username ILIKE ?"). the ILIKE or similar syntax is dependant on your database though.




回答2:


Another option could be:

def self.search(query)
    where("lower(name) LIKE lower(?)", "%#{query}%") 
end

This would work in sqlite or in PostgreSQL.




回答3:


You can use Arel Tables.

# Suppose the target username in DB is 'FooBAR'.
t = User.arel_table
@user = User.find_by(t[:username].matches 'foobar')

This will find users with usernames like 'FooBar', 'foobar', 'FOOBAR' and so on.

More details here: https://github.com/rails/arel.



来源:https://stackoverflow.com/questions/54911348/case-insensitive-to-joins-table-active-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!