3

I am building a authorization framework that will eventually use cancan at the code level. I am creating the model and associations and have things almost perfect, but I ran into a snag.

I have User, Roles and Rights with many to many join tables (user_roles and role_rights) and I have things setup so that you can do User.roles and User.roles.first.rights but I would like to be able to do User.rights

class User < ActiveRecord::Base
  has_many :user_roles
  has_many :roles, :through => :user_roles
end

class UserRole < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
end

class Role < ActiveRecord::Base
  has_many :user_roles
  has_many :users, :through => :users_roles
  has_many :role_rights
  has_many :rights, :through => :role_rights
end

class RoleRight < ActiveRecord::Base
  belongs_to :role
  belongs_to :right
end

class Right < ActiveRecord::Base
  has_many :role_rights
  has_many :roles, :through => :role_rights
end

The following works:

User.roles

so does this:

User.roles.first.rights

but what I want to do is:

User.rights

but when I try, I get the follow error: NoMethodError: undefined method `rights'

I assume that I need to add something to the User model to let it transverse to the Right model but I can't figure out the associations.

I'm using Rails 2.3.4 and Ruby 1.8.7

Aaron Park
  • 75
  • 6
  • The association methods works on an model instance rather than a model class. OTH, what are you trying to retrieve? – Harish Shetty Mar 21 '12 at 18:36
  • Nested `has_many :through` is not supported in rails 2.3.x( it is supported in Rails 3.1 and above). Refer to this answer(http://stackoverflow.com/questions/2383479/ruby-on-rails-multiple-has-many-through-possible/2383560#2383560) to find out how you can support it in Rails 2.3.x. – Harish Shetty Mar 21 '12 at 18:41
  • did you try the proposed solution? Look after the questions you make! – tokland Jul 05 '13 at 06:33

1 Answers1

1

Try something like this:

class User < ActiveRecord::Base
   def self.rights
     Right.joins(:roles => :user).all("users.id = ?", self.id)
   end
end
gayavat
  • 18,910
  • 11
  • 45
  • 55