ActiveRecord find starts with

前端 未结 8 1915
走了就别回头了
走了就别回头了 2021-01-30 05:33

Really simple question - how do I do a search to find all records where the name starts with a certain string in ActiveRecord. I\'ve seen all sorts of bits all over the internet

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 05:47

    Disclaimer: I am new to Ruby and Rails, and I am still trying to learn the Ruby Way to do things, but I have been coding for more than half of my life, and professionally for a decade. DRY is a concept with which I am very familiar. Here is how I implemented it. It is very similar to narsk's answer, which I think is also good.

    # name_searchable.rb
    # mix this into your class using
    #   extend NameSearchable
    module NameSearchable
      def search_by_prefix (prefix)
        self.where("lower(name) LIKE '#{prefix.downcase}%'")
      end
    end
    

    And then in your model:

    class User < ActiveRecord::Base
      extend NameSearchable
      ...
    end
    

    And then when you want to use it:

    User.search_by_prefix('John')   #or
    User.search_by_prefix("#{name_str}")
    

    One thing to call out:

    Traditional relational databases aren't extremely good at satisfying these kinds of queries. If you are looking for a highly responsive implementation that will not kill your databases under load, you should probably use a solution that is tailored to the purpose instead. Popular examples include Solr or Sphinx, and there are many others as well. With this implementation, since you DRY, you could substitute the implementation with a separate indexer in just one place and you would be ready to rock.

提交回复
热议问题