2012-03-21 87 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