ActiveRecord find starts with

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

    Very much like the above answer, but if you're using ActiveRecord...2.1 or greater, you could use a named scope which would allow you to use this "finder" on records retrieved thru associations:

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

    Used like:

    User.with_name_like("Samson")
    

    (returns all users in your database with a name like "Samson".

    Or:

    some_association.users.with_name_like("Samson")
    

    Users off that association only with a name like "Samson".

提交回复
热议问题