Rails的搜索与可选参数? [英] Rails Search with optional parameters?

查看:108
本文介绍了Rails的搜索与可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于Rails的搜索与可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆