Ruby on rails 如何在activerecord中遍历多个多对多关联

Ruby on rails 如何在activerecord中遍历多个多对多关联,ruby-on-rails,activerecord,associations,Ruby On Rails,Activerecord,Associations,我正在构建一个授权框架,最终将在代码级别使用cancan。我正在创建模型和关联,并且拥有近乎完美的东西,但我遇到了一个障碍 我有多对多联接表的用户、角色和权限(用户角色和角色权限),我有一些设置,以便您可以执行User.Roles和User.Roles.first.Rights,但我希望能够执行User.Rights class User < ActiveRecord::Base has_many :user_roles has_many :roles, :through =>

我正在构建一个授权框架,最终将在代码级别使用cancan。我正在创建模型和关联,并且拥有近乎完美的东西,但我遇到了一个障碍

我有多对多联接表的用户、角色和权限(用户角色和角色权限),我有一些设置,以便您可以执行User.Roles和User.Roles.first.Rights,但我希望能够执行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
这也是:

User.roles.first.rights
但我想做的是:

User.rights
但是当我尝试时,我得到了以下错误:NoMethodError:undefined方法'rights'

我假设我需要向用户模型中添加一些东西,使其与正确的模型交叉,但我无法找出关联


我正在使用Rails 2.3.4和Ruby 1.8.7

class User < ActiveRecord::Base
   def self.rights
     Right.joins(:roles => :user).all("users.id = ?", self.id)
   end
end
class用户:user).all(“users.id=?”,self.id)
结束
结束

关联方法适用于模型实例,而不是模型类。另外,您想检索什么?嵌套的
有很多:通过
在rails 2.3.x中不受支持(在rails 3.1及更高版本中受支持)。请参考此答案()了解如何在Rails 2.3.x中支持它。您是否尝试了建议的解决方案?注意你提出的问题+1嵌套的
在Ruby 3中有许多
的工作,但这是Rails 2中唯一的方法。
class User < ActiveRecord::Base
   def self.rights
     Right.joins(:roles => :user).all("users.id = ?", self.id)
   end
end