ActiveRecord find starts with

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

    If you're looking to do the search in the database then you'll need to use SQL.

    And, of course, you'll need to do the search in the database otherwise you need to load all the objects into Ruby (which isn't a good thing).

    So, you will need something like

    MyModel.find(:all, :conditions => ["field LIKE ?", "#{prefix}%"])
    

    where prefix is a variable with the string you're looking for.

    In Rails 3.0+ this becomes:

    MyModel.where("field LIKE :prefix", prefix: "#{prefix}%")
    

提交回复
热议问题