ActiveRecord find starts with

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

    I would highly recommend the Searchlogic plugin.

    Then it's as easy as:

    @search = Model.new_search(params[:search])
    @search.condition.field_starts_with = "prefix"
    @models = @search.all
    

    Searchlogic is smart enough, like ActiveRecord, to pick up on the field name in the starts_with condition. It will also handle all pagination.

    This method will help prevent SQL injection and also will be database agnostic. Searchlogic ends up handling the search differently depending on the database adapter you're using. You also don't have to write any SQL!

    Searchlogic has great documentation and is easy to use (I'm new to Ruby and Rails myself). When I got stuck, the author of the plugin even answered a direct email within a few hours helping me fix my problem. I can't recommend Searchlogic enough...as you can tell.

提交回复
热议问题