以下问题:
我需要一个空范围之类的东西。这意味着这个作用域是emtpy的,但它响应作用域通常响应的所有方法。我现在用的是一个下流的小技巧。我只是简单地提供"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
https://stackoverflow.com/questions/3735838
复制相似问题