更好的搜索查询两列forename和name

时间:2013-11-12 18:40:29

标签: ruby-on-rails ruby ruby-on-rails-3 sqlite ruby-on-rails-4

实际上我有来自MrJoshi的搜索查询,这是相关的问题: Search query for (name or forename) and (name forname) and (forname name)

def self.search(query)
  return where('FALSE') if query.blank?

  conditions = []
  search_columns = [ :forname, :name ]

  query.split(' ').each do |word|
    search_columns.each do |column|
      conditions << " lower(#{column}) LIKE lower(#{sanitize("%#{word}%")}) "
    end
  end

  conditions = conditions.join('OR')    
  self.where(conditions)
end

此搜索查询的问题在于它返回多条记录的方式。例如,如果某人正在搜索John Smith,则此搜索查询将返回forename John的所有记录以及name Smith的所有记录,尽管只有一个人与搜索查询完全匹配意味着{{} 1}} 所以我改变了一点代码:

name is Smith and forename is John

但现在我收到了这个错误:

def self.search(query)
  return where('FALSE') if query.blank?

  conditions = []

  query2 = query.split(' ')

  if query2.length == 2
      conditions << " lower(:forname) AND lower(:name) LIKE ?', lower(#{sanitize("%#{query2.first}%")}) , lower(#{sanitize("%#{query2.last}%")})"
      conditions << " lower(:forname) AND lower(:name) LIKE ?', lower(#{sanitize("%#{query2.last}%")}) , lower(#{sanitize("%#{query2.first}%")})"
  else
    search_columns = [ :forname, :name ]
       query2.each do |word|
        search_columns.each do |column|
         conditions << " lower(#{column}) LIKE lower(#{sanitize("%#{word}%")}) "
        end
       end
  end

  conditions = conditions.join('OR')    
  self.where(conditions)
end 

我错了什么?谢谢!

0 个答案:

没有答案