2012-03-21 96 views
2

我正在构建一个授权框架,最终将在代码级使用cancan。我正在创建模型和关联,并且拥有几乎完美的东西,但我碰到了一个障碍。如何遍历积极记录中的多个多关联

我有用户,角色和权利与多对多的连接表(user_roles和role_rights),我有东西安装,以便您可以做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 

那么,这是否:

User.roles.first.rights 

但我想要做的是:

User.rights 

但是当我尝试,我得到了如下错误:NoMethodError:未定义的方法`权利

我认为我需要的东西添加到用户模型让它横向到正确的模式,但我无法弄清楚这些关联。

我用Rails 2.3.4和Ruby 1.8.7

+0

的关联方法上的模型实例,而不是一个模型类的工作。哦,你想要找回什么? – 2012-03-21 18:36:27

+0

在rails 2.3.x中不支持嵌套'has_many:through'(它在Rails 3.1及更高版本中受支持)。请参阅此答案(http://stackoverflow.com/questions/2383479/ruby-on-rails-multiple-has-many-through-possible/2383560#2383560)以了解如何在Rails 2.3.x中支持它。 – 2012-03-21 18:41:00

+0

您是否尝试过建议的解决方案?照顾你所做的问题! – tokland 2013-07-05 06:33:02

回答

1

尝试是这样的:

class User < ActiveRecord::Base 
    def self.rights 
    Right.joins(:roles => :user).all("users.id = ?", self.id) 
    end 
end 
+0

+1嵌套'has_many'在Ruby 3中工作,但AFAIK这是Rails 2中唯一的方法。 – tokland 2013-07-05 06:32:34