多范围轨道

时间:2012-02-13 16:13:54

标签: ruby-on-rails scope

class Anketum < ActiveRecord::Base
  has_one :user 

  class << self
    def search(params)
      self.scope :h, :conditions => {:height => params[:height]}
      #scope :w, :conditions => {:width => params[:width]}
      self.h if params[:height]
    end

  end
end

我需要根据params [:xxx] present

创建多个范围

1 个答案:

答案 0 :(得分:1)

根据您的代码示例判断,您过度设计了这个:

# app/models/anketum.rb
class Anketum < ActiveRecord::Base
end

# app/controller/some_controller.rb
def search
  @results = Anketum.scoped
  [:width, :height, :any, :other, :searchable, :attribute].each do |key|
    @results.where(key => params[key]) if params[key].present?
  end
end

顺便说一下,你的模型永远不应该访问params哈希。