2010-12-18 36 views

cevap

17

Bir sorgu birikebilir:

conditions = {} 
conditions[:city] = city unless city.blank? 
conditions[:zip] = zip unless zip.blank? 
conditions[:state] = state unless state.blank? 
Address.find(:all, :conditions => conditions) 
+0

ben ama bunu yapabilirim nasıl parametre birinde koşulu daha büyük olan mongoid sorgunun aynı tür çalıştırmak gerekirse lütfen bana ? Umarım anlarsın! –

31

olağan danışma modeline mantığı taşımak ve mümkün olduğunca yalın kontrolörü tutmaktır. filtre yöntemi için farklı yaklaşımlar, ilk vardır: şu anda ActionController kullanır Raylar 5 için

class Record < ActiveRecord::Base 
    SUPPORTED_FILTERS = [:id, :city, ...] 
    scope :id, ->(value) { where(id: value) } 
    scope :city, ->(value) { where(city: "%#{value}%") } 
    ... 

    def self.filter(attributes) 
    attributes.slice(*SUPPORTED_FILTERS).reduce(all) do |scope, (key, value)| 
     value.present? ? scope.send(key, value) : scope 
    end 
    end 
end 

:

class Record < ActiveRecord::Base 
    def self.filter(attributes) 
    attributes.select { |k, v| v.present? }.reduce(all) do |scope, (key, value)| 
     case key.to_sym 
     when :id, :zip # direct search 
     scope.where(key => value) 
     when :city, :state # regexp search 
     scope.where(["#{key} ILIKE ?", "%#{value}%"]) 
     when :order # order=field-(ASC|DESC) 
     attribute, order = value.split("-") 
     scope.order("#{self.table_name}.#{attribute} #{order}") 
     else # unknown key (do nothing or raise error, as you prefer to) 
     scope 
     end 
    end 
    end 
end 

ikinci bir yaklaşım, sadece mevcut kapsamları kullanan bir çıplak filter geç: : Parametreler, filtre yöntemi için sözdizimi şöyledir:

def self.filter(attributes) 
    attributes.permit(SUPPORTED_FILTERS).to_hash.reduce(all) do |scope, (key, value)| 
    value.present? ? scope.send(key, value) : scope 
    end 
end 

Modelleri yerde uygulamanızda çağrılabilir, böylece yeniden kullanılabilir ve test etmek daha kolaydır edilebilir.

class RecordsController < ApplicationController::Base 
    respond_to :html, :xml 

    def index 
    @records = Record.filter(params) 
    end 
end 
+1

+1 denetleyiciyi basit tutmanın iyi bir yolu – zetetic

+1

@tokland Çözümünüzü kullandım. Http://railscasts.com/episodes/112-anonymous-scopes ve http://railscasts.com/episodes/111-advanced-search-form adresinden daha zarif görünüyor. Çok teşekkürler! –

+0

Bu çözümde potansiyel bir bellek sızıntısı/DoS saldırısı güvenlik açığı yok mu? Ex, birisi büyük sorgu dizeleri göndermeye devam ediyor ve model rastgele sorgu dizeleri key.to_sym'ing tutar? –

0

http://metautonomo.us/projects/metasearch/ ne ihtiyaç vardır: gibi şimdi kontrolör gibi basit görünüyor. Sonra

= text_field_tag 'search[city_like]', '' 
= text_field_tag 'search[zip_equals]', '' 
= text_field_tag 'search[state_equals]', '' 

Ve sadece

Record.search(params[:search]) 
İlgili konular