问题描述
|
我不知道有没有可能?我需要在/范围内使用实例方法。像这样:
scope :public,lambda{ where ({:public => true}) }
并在每条记录上调用实例方法(complete?)以查看其是否完成。 public范围应在此处返回所有公开且已完成的记录,并且记录的完成情况由实例方法“ complete?\”确定
有没有可能
谢谢
解决方法
范围涉及使用ARel生成查询逻辑。如果不能代表完整的逻辑? SQL中的方法,那么您有点卡住
范围-至少在rails 3中-是用于将查询逻辑链接在一起而不返回结果集。如果您需要一个结果集来完成测试,则需要执行以下操作
class MyModel < ActiveRecord::Base
scope :public,lambda{ where ({:public => true}) }
def self.completed_public_records
MyModel.public.all.select { |r| r.completed? }
end
end
# elsewhere
MyModel.completed_public_records
或者,如果您需要更大的灵活性
class MyModel < ActiveRecord::Base
scope :public,lambda{ where ({:public => true}) }
# some other scopes etc
def self.completed_filter(finder_obj)
unless finder_obj.is_a?(ActiveRecord::Relation)
raise ArgumentError,\"An ActiveRecord::Relation object is required\"
end
finder_obj.all.select { |r| r.completed? }
end
end
# elsewhere
MyModel.completed_filter(MyModel.public.another_scope.some_other_scope)
, 几个月前,当我遇到同样的问题时,我为这个确切的问题创建了一个rubygem。
它允许您添加对查询结果集起作用的方法,但是将方法抽象到另一个类中,这样就不会与模型混淆。
检查一下:https://github.com/coryodaniel/collectively