使用 AssistantTeacher 类中的新属性marked_deleted,我们希望所有查询都可以在仅选择marked_deleted 属性为false 的基本假设下工作。
这很容易(使用 squeel 查询语言而不是标准的 AR 查询语言)
class AssistantTeacher < ActiveRecord.Base
# Gives a default query which always includes the condition here
default_scope {where{marked_deleted == false }}
end
这意味着像AssistantTeacher.all这样的查询实际上是
AssistantTeacher.all.where{marked_deleted == false}
效果很好。同样,AssistantTeacher.find_each() 也适用于限制。同样地
AssistantTeacher.where{atcode == "MPL"}
也执行为
I
然而,棘手的部分是:在特殊情况下,我们需要为管理员等反转 default_scope:
class AssistantTeacher < ActiveRecord.Base
# Gives a default query which always includes the condition here
default_scope {where{marked_deleted == false }}
# If a query is unscoped then the default_scope limitation does not apply
# scoped is the default scope when there is no default_scope
unscoped { scoped}
end
这适用于
def self.all_including_marked_deleted
return unscoped{all}
end
但是:我无法弄清楚如何使用块为 find_each 的管理员版本做一个无范围的问题
def self.find_each_including_marked_deleted &block
return unscoped{find_each(block)}
end
不工作。也没有我能想到的任何其他与块的组合。
任何人都知道我可以做些什么来让我的覆盖方法 find_each_including_marked_deleted 将其块传递给无范围调用?