Case insensitive active record query in rails-4

前端 未结 3 1895
被撕碎了的回忆
被撕碎了的回忆 2021-01-06 03:35

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 p

相关标签:
3条回答
  • 2021-01-06 03:56

    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.

    0 讨论(0)
  • 2021-01-06 04:09

    Another option could be:

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

    This would work in sqlite or in PostgreSQL.

    0 讨论(0)
  • 2021-01-06 04:14

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

    0 讨论(0)
提交回复
热议问题