I'm trying to define a named_scope for all my models in a Rails application.
Presently, I've been able to get close to this by writing an initializer for ActiveRecord::Base and putting regular methods in there. Of course, this offers no real advantage when it comes to creating query chains and is probably the least rails-ey way of getting the job done.
However, it doesn't work when I start to try and use the has_many, named_scope, etc... ActiveRecord methods.
While I understand my named_scope is likely not correct, I really only want help getting the named_scope defined. Also, I am not interested in any Ruby ACL GEMs at present.
In initializers/:
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