bik*_*shp 6 scope ruby-on-rails-3
我不知道它可能吗?我需要在范围内使用实例方法.像这样的东西:
scope :public, lambda{ where ({:public => true}) }
Run Code Online (Sandbox Code Playgroud)
并在每条记录上调用实例方法(完成?)以查看它是否已完成.这里的公共范围应该返回所有公开的记录并完成记录,记录的完成由实例方法"完成"确定.
有可能吗?
谢谢
Chr*_*ley 11
范围是关于使用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
Run Code Online (Sandbox Code Playgroud)
或者如果您需要更多灵活性
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9944 次 |
| 最近记录: |