【问题标题】:Search many fields with will_paginate / searchlogic使用 will_paginate / searchlogic 搜索多个字段
【发布时间】:2010-11-14 07:55:08
【问题描述】:

您如何有效地在模型中的多个字段中进行搜索?

# user.rb model
def self.search(search, page)  
  paginate :per_page => 20, :page => page,
  :conditions => 
    ['name like ? OR notes like ? OR code like ? OR city like ? OR state like ?,
    "%#{search}%","%#{search}%","%#{search}%","%#{search}%","%#{search}%"
    ], :order => 'name'

这段代码对于几个字段来说都是可怕的,并且如果例如单词#1来自:name而单词#2来自:code,它不会返回结果。有没有更优雅的方式?

【问题讨论】:

  • 你知道吗,好电话。我会把它们拆散。
  • 搜索没有找到与多个单词匹配的原因是因为它正在所有列中查找整个字符串“word1 word2”,但只找到部分匹配项,因此请务必分开首先是搜索词。

标签: ruby-on-rails ruby-on-rails-3 will-paginate searchlogic


【解决方案1】:

我认为这行得通

def self.search(search, page)
  fields = [:name, :notes, :code, :city, :state] 
  paginate :per_page => 20, :page => page,
  :conditions => [fields.map{|f| "#{f} like ?"}.join(' OR '),
    *fields.map{|f| "%#{search}%"}], :order => 'name'

【讨论】:

  • 感谢您将其压缩得如此出色。我用两个搜索词尝试了它,一个来自 :notes 另一个来自 :code 并且它不起作用(之前它也不起作用)。有没有办法跨字段为每个搜索词添加结果?
【解决方案2】:

您可以使用searchlogic

def self.search(search, page)  
  search_cond = resource.search(name_or_notes_or_code_or_city_or_state_like => search.to_s)
  search_cond.all
end

希望你明白了

【讨论】:

    【解决方案3】:
    def self.search(search, page)
      fields = %w(name notes code city state) 
      paginate :per_page => 20, :page => page,
      :conditions => [fields.map{|f| "#{f} like :phrase"}.join(' OR '), {:phrase => search}], 
      :order => 'name' 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多