ActiveRecord find starts with

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

    Now it's 2012 I thought I'd throw in this update to narsk's answer.

    named_scope became simply scope a while ago so the example becomes

    class User
      scope :name_starts_with, lambda {|str|
        :conditions => ['lower(name) like ?', "#{str.downcase}%"]
      }
    end
    

    Note I removed the first % from narsk's solution as the OP is asking for a 'starts_with' not a 'contains' match.

    Now you can do things like

    User.name_starts_with("b").each do {|bs| puts bs.inspect}
    bob = User.name_starts_with("bob").first
    
    … etc
    

    Note that scopes always return collections, never individual results. That threw me when I was first starting out with AR and I still manage to forget that every now and again.

提交回复
热议问题