Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
774 views
in Technique[技术] by (71.8m points)

ruby - Rails Search with optional parameters?

How would I do a search on a database when the search can provide many optional parameters such as ID, Zip, City, and State? These can either have values or be blank entirely. How would I make a rails query like that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The usual advice is to move logic to the model and keep the controller as lean as possible. There are different approaches for the filter method, the first one:

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

A second approach, write a bare filter that only uses existing scopes:

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

For Rails 5, which now uses ActionController::Parameters, the syntax for the filter method is:

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

Models can be called from anywhere in your app, so they are re-usable and easier to test. Now the controller looks as simple as:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...