不幸的是,你已经打在ActiveRecord的查询API的痛处。没有标准,开箱即可这样做。你可以很容易地做日期范围,但<
和>
没有简单的路径。但是,底层的SQL引擎Arel可以非常轻松地完成此操作。你可以写一个简单的范围,正是如此处理:
scope :created_after, lambda {|date| where arel_table[:created_at].gt(date) }
你可以重构这一点很容易采取一列,或gt
与lt
等
其他人已经解决了这个问题,但是,你可以利用他们的工作。一个例子是MetaWhere,它为您的查询添加了一堆语法糖。例如,使用它你可能会写:
Article.where(:title.matches => 'Hello%', :created_at.gt => 3.days.ago)
在#2上,范围确实会变长。您可以查看gem has_scope,这有助于通过在控制器上定义范围,以类似于在模型上定义它们的方式来缓解此问题。来自网站的示例:
# The model
# Note it's using old Rails 2 named_scope, but Rails 3 scope works just as well.
class Graduation < ActiveRecord::Base
named_scope :featured, :conditions => { :featured => true }
named_scope :by_degree, proc {|degree| { :conditions => { :degree => degree } } }
end
# The controller
class GraduationsController < ApplicationController
has_scope :featured, :type => :boolean
has_scope :by_degree
def index
@graduations = apply_scopes(Graduation).all
end
end