views:

451

answers:

1

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
+1  A: 

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.

Ben Hughes
Is there any alternative method that I can use to go about adding named_scopes to all models in my app?Normally I'm ok with the methods, but then they can't participate in a chain the way a named_scope could. There's also way more query activity and overhead in using a simple method....
Omega
define named scopes as you are doing, it works in my application. alternatively, you can use regular inheritance using an abstract activerecord class like http://www.harukizaemon.com/2006/10/abstract-activerecord-classes-by.html. To get the has_many, etc. you will most likely have to add a method call (either has many or custom function) to each model's class body
Ben Hughes
Using an abstract class would require that all my models extend THAT class instead though, right?
Omega
inherit from. But if you create a module that the models include, you can use the included? hook to do everything you ever dreamed of
Ben Hughes