Ruby on rails 多范围轨道
我需要根据params[:xxx]present创建多个作用域根据您的代码示例判断,您已经完成了以下工程:Ruby on rails 多范围轨道,ruby-on-rails,scope,Ruby On Rails,Scope,我需要根据params[:xxx]present创建多个作用域根据您的代码示例判断,您已经完成了以下工程: class Anketum < ActiveRecord::Base has_one :user class << self def search(params) self.scope :h, :conditions => {:height => params[:height]} #scope :w, :condit
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
顺便说一下,您的模型不应该访问参数散列。原因不起作用的地方。。。奇怪的选择anketa.*从anketa中选择db表也叫anketa吗?如果不是,您的设置有很大问题。您使用的是哪个Rails版本?我假设为3,因为您使用的是scope而不是命名的_scope.Rails 3。你们提出了一个很好的解决方案,但我认为在我的任务中,我无法逃避复杂的sql查询——你们用错了AR;这是一个常见的问题。你没有做一个复杂的查询——你打破了关注点和过度工程的分离。对不起,我是迪克,但谷歌一下。
# 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