Search on multiple keywords in a single search text field (RAILS)

前端 未结 3 751
你的背包
你的背包 2020-12-18 11:12

I\'m fairly new and playing around with searching databases in Rails. I have a model and database that has a list of names under the \'name\' attribute. I want to be able to

3条回答
  •  爱一瞬间的悲伤
    2020-12-18 11:37

    Use something like this:

    find(:all, :conditions => [(['name LIKE ?'] * search_length).join(' AND ')] + search.split.map { |name| "%#{name}" })
    

    I looks strange but, first generate search_length times string 'name LIKE ?':

     ['name LIKE ?'] * search_length
    

    then you have array with some keys, so let's join all of them with ' AND ':

     ["name LIKE ? ", "name LIKE ? ", "name LIKE ? "].join(' AND ')
    

    and finally merge with another array.

提交回复
热议问题