2010-11-14 69 views
2

如何在模型中的許多字段之間進行有效搜索?使用will_paginate/searchlogic搜索很多字段

# 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來自它不返回結果:名字和詞#2來自:代碼。有沒有更優雅的方式?

+0

爲什麼不做兩個問題? – shingara 2010-11-14 08:05:19

+0

你知道嗎,很好的電話。我會打破他們。 – sscirrus 2010-11-14 08:05:46

+0

搜索沒有找到與多個單詞匹配的原因是因爲它在所有列中查找整個字符串「word1 word2」,但僅查找部分匹配項,因此請確保首先分隔搜索項。 – Rich 2011-02-22 23:39:04

回答

2

我覺得做的工作

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' 
+0

非常感謝你壓縮它。我試了兩個搜索詞,其中一個來自:筆記和另一個來自:代碼,它不起作用(它之前沒有工作)。有什麼方法可以爲每個搜索字詞添加結果嗎? – sscirrus 2010-11-14 08:18:07

0
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' 
1

您可以使用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 

希望你有這個想法