从日期x开始尝试为记录创建rails模型范围查询,使用lambda?

我想我会想要使用模型级查找器和lambda。

named_scope :recent_snaps, lambda {|since_when| {:conditions=>{:created_at >= since_when}}} 

但我不确定,如果我的语法正确,特别是参数片,并且无法立即运行应用程序来检查控制台。

我不想使用find_by_sql或控制器查找,我希望我的finder在模型级别进行rspec测试。

如果您使用的是Rails 3(因为您可能是问题的标签),您应该使用scope而不是named_scope而不是conditions 。 此外,您不能在哈希中使用>=

您完成的范围应如下所示:

 scope :recent_snaps, lambda { |since_when| where("created_at >= ?", since_when) } 

为了补充Alex的答案:对于你正在尝试的查询的外观,我想你会喜欢吱吱 :

 scope :recent_snaps, lambda { |since_when| where{created_at >= since_when} } 

只是其他方法来实现相同(至少在rails 3.1中)

在平轨中

scope :recent_snaps, ->(since_when) { where("created_at >= ?", since_when) }

轨道+ squeel

scope :recent_snaps, ->(since_when) { where{created_at >= since_when} }