ActiveRecord find starts with

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

    Very terse syntax for the same thing might be:

    Model.where(field: ('prefix'...'prefiy'))
    

    This renders:

    WHERE ( field >= 'prefix' AND field < 'prefiy')
    

    This does the job as 'prefiy' is the first string alphabetically not matching the 'prefix' prefix.

    I would not use it normally (I would go for squeel or ransack instead), but it can save your day if for some reason you have to stick to hash syntax for the queries...

提交回复
热议问题