ActiveRecord find starts with

前端 未结 8 1911
走了就别回头了
走了就别回头了 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

    I don't want to write a scope every time I want to see if a specific column starts_with a prefix.

    # initializers/active_record_initializers.rb
    class ActiveRecord::Base
      # do not accept a column_name from the outside without sanitizing it
      # as this can be prone to sql injection
      def self.starts_with(column_name, prefix)
        where("lower(#{column_name}) like ?", "#{prefix.downcase}%")
      end
    end
    

    Call it like this:

    User.starts_with('name', 'ab').limit(1)
    

提交回复
热议问题