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

前端 未结 3 744
你的背包
你的背包 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.

    0 讨论(0)
  • 2020-12-18 11:41

    The code from Łukasz Śliwa works great if you close the name variable with the other % sign.

    The complete code from above working for me. Great post.

    def self.search(search)
    
      if search
        search_length = search.split.length
        find(:all, :conditions => [(['name LIKE ?'] * search_length).join(' AND ')] + search.split.map { |name| "%#{name}%" })
      else
        find(:all)
      end
    
    end
    
    0 讨论(0)
  • 2020-12-18 11:50
    formatted_columns = format_column_names(Sub.column_names)
    where(formatted_columns.map {|cn| "#{cn} like ?" }.join("or "), *(["%#{search}%"] * formatted_columns.size))
    

    this takes care of all columns as well as the correct amount of fields

    0 讨论(0)
提交回复
热议问题