Rails的搜索与可选参数?可选、参数、Rails

由网友(掐指一算,你能活到死)分享简介:我将如何做时,搜索可以提供许多可选参数,如身份证,邮编,城市和国家数据库的搜索?这些可以有价值观是完全空白的。我将如何做一个滑轨查询这样呢?How would I do a search on a database when the search can provide many optional parameter...

我将如何做时,搜索可以提供许多可选参数,如身份证,邮编,城市和国家数据库的搜索?这些可以有价值观是完全空白的。我将如何做一个滑轨查询这样呢?

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?

推荐答案

通常的建议是将逻辑模型,并保持控制器精益越好。有些方法为模型:第一个,写了过滤器类方法,通过键/值实现搜索:

The usual advice is to move logic to the model and keep the controller as lean as possible. Some approaches for the model: the first one, write a filter classmethod that implements the search by key/value:

class Record < ActiveRecord::Base
  def self.filter(attributes)
    attributes.reduce(scoped) do |scope, (key, value)|
      return scope if value.blank?
      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

第二种方法,写一个光秃秃的过滤器只是用现有的AR范围的方法:

A second approach, write a bare filter method that just uses existing AR scopes:

class Record < ActiveRecord::Base
  scope :id, lambda { |value| scope.where(:id => value) }
  scope :city, lambda { |value| scope.where(:city => "%#{value}%") }
  ...

  def self.filter(attributes)
    supported_filters = [:id, :city, ...]
    attributes.slice(*supported_filters).reduce(scoped) do |scope, (key, value)|
      value.present? ? scope.send(key, value) : scope
    end  
  end
end

模型可以从你的应用程序的任何地方调用,因此它们是可重复使用的,更简单的测试。现在,控制器可能看起来那样简单:

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

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

  def index
    @records = Record.filter(params)
  end
end
阅读全文

相关推荐

最新文章