我正在尝试为 Rails 应用程序中的所有模型定义一个 named_scope。
目前,我已经能够通过为 ActiveRecord::Base 编写一个初始化程序并将常规方法放入其中来接近这一点。当然,这在创建查询链时并没有提供真正的优势,并且可能是完成工作的最简单的方式。
但是,当我开始尝试使用 has_many、named_scope 等... ActiveRecord 方法时,它不起作用。
虽然我知道我的 named_scope 可能不正确,但我真的只想帮助定义 named_scope。另外,我目前对任何 Ruby ACL GEM 都不感兴趣。
在初始化器/中:
class ActiveRecord::Base
has_many(:permissions)
named_scope(:acl_check, lambda do |user_id, method|
{
:include => :permission,
:conditions => [
["permissions.user_id=?", user_id],
["permissions.method=?", method],
["permissions.classname=?", self.class.name]
]
}
end)
# Conducts a permission check for the current instance.
def check_acl?(user_id, method)
# Perform the permission check by User.
permission_check = Permission.find_by_user_id_and_instance_id_and_classname_and_method(user_id, self.id, self.class.name, method)
if(permission_check)
# If the row exists, we generate a hit.
return(true)
end
# Perform the permission check by Role.
# Otherwise, the permissions check was a miss.
return(false)
end
end