Question

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
Was it helpful?

Solution

the has_many will likely not work because it is evaluated in the class body and the expected foreign keys are for the class in which it was evaluated rather than the inheriting classes. (e.g. Blog model with id=42 can have many Comment models stored with blog_id = 42, the keys that are needed to make it work are based on the class name)

The named scope should work if it is correct.

The inherited method should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top