【问题标题】:How to traverse multiple many to many associations in activerecord如何在activerecord中遍历多个多对多关联
【发布时间】:2012-04-06 07:31:39
【问题描述】:

我正在构建一个最终将在代码级别使用 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: undefined method `rights'

我假设我需要在 User 模型中添加一些内容以使其横向于 Right 模型,但我无法确定关联。

我正在使用 Rails 2.3.4 和 Ruby 1.8.7

【问题讨论】:

  • 关联方法适用于模型实例而不是模型类。 OTH,您要检索什么?
  • Rails 2.3.x 不支持嵌套has_many :through(Rails 3.1 及更高版本支持)。请参阅此答案 (stackoverflow.com/questions/2383479/…) 以了解如何在 Rails 2.3.x 中支持它。
  • 您尝试过建议的解决方案吗?注意你提出的问题!

标签: ruby-on-rails activerecord associations


【解决方案1】:

试试这样的:

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

【讨论】:

  • +1 嵌套 has_many 在 Ruby 3 中工作,但 AFAIK 这是 Rails 2 中唯一的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-26
相关资源
最近更新 更多