【发布时间】:2010-09-17 13:45:47
【问题描述】:
以下问题:
我需要一个空范围之类的东西。这意味着这个范围是空的,但响应范围通常响应的所有方法。
我目前正在使用一些肮脏的技巧。我只是提供“1=0”作为条件。我觉得这真的很难看,因为它会命中数据库。简单地返回一个空数组是行不通的,因为结果必须响应作用域方法。
是否有更好的现有解决方案或者我需要自己编写代码?
也许一些示例代码可以帮助解释我需要什么:
class User < ActiveRecord::Base
named_scope :admins, :conditions => {:admin => true }
named_scope :none_dirty, :conditions => "1=0" # this scope is always empty
def none_broken
[]
end
def self.sum_score # okay, a bit simple, but a method like this should work!
total = 0
self.all.each do |user|
total += user.score
end
return total
end
end
User.admin.sum_score # the score i want to know
User.none_drity.sum_score # works, but hits the db
User.none_broken.sum_score # ...error, since it doesn't respond to sum_score
【问题讨论】:
-
为什么空集的分数永远不会是 0?你想在这里完成什么?
-
您正在寻找一个空集合。
-
@jdl:不会是 0 以外的东西。