2014-10-19 67 views
0

我正在尋找一種使用給定的列/值散列構建過濾器查詢的簡單方法。所有的值都應該用在LIKE查詢中。我可以建立查詢,並在陣列中的參數,並把它傳遞到哪裏,就像這樣:Rails使用LIKE簡單過濾

def self.filter(filters=nil) 

    if filters.nil? || filters.empty? 
    return all 
    end 

    query = [] 
    value_array = [] 
    filters.each do |key, value| 
     query << "#{key} LIKE ?" 
     value_array << "%#{value}%" 
    end 

    where([query.join(' AND ')] + value_array) 

    end 

但我不知道是否有這樣做是內置到Rails(使用第4版)或更好的方法如果有一個超級簡單的寶石可以輕鬆接受並變成LIKE濾鏡?

回答

1

一個很好的方式在查詢中發揮好與哈希值是利用散列#切片方法和範圍的:

... 
filtering_params(params).each do |key, value| 
    @products = @products.public_send(key, value) if value.present? 
end 

def filtering_params(params) 
params.slice(:status, :location, :starts_with) 
end 

class Product < ActiveRecord::Base 
    scope :status, -> (status) { where status: status } 
    scope :location, -> (location_id) { where location_id: location_id } 
    scope :starts_with, -> (name) { where("name like ?", "#{name}%")} 
end 

here服用。畢竟,您可能需要將邏輯限制在DSL中的某些特定查詢中。