【问题标题】:Is there a way to have three way habtm associations in rails / activerecord?有没有办法在 rails / activerecord 中建立三向 habtm 关联?
【发布时间】:2011-02-17 19:41:43
【问题描述】:

habtm 关联通常需要三种(或更多)方式关联。例如具有角色的权限模型。

一个特定的功能区域有许多用户可以访问许多区域。

该区域的权限是通过角色(habtm)设置的

用户/角色关联也是 habtm

权限(读取、写入、删除等)是针对角色的。

如何最好地使用 rails/activerecord?

【问题讨论】:

  • 我不确定你在这里问什么。可能值得添加一些示例代码来说明您希望如何访问数据。假设您的要求是可能的,请举例说明您如何使用它。

标签: ruby-on-rails orm activerecord


【解决方案1】:

This question about rails and RBAC(基于角色的身份验证控制)有一堆有用的示例,可以提供此问题的答案以及示例的示例实现。

【讨论】:

    【解决方案2】:

    我不确定您是否只是使用基于角色的用户权限作为示例,或者这实际上是您的目标。

    嵌套 habtm 关系在 Rails 中很容易,但我强烈推荐嵌套 has_many :through,只需按照您的想象设置即可:

    class Permission < ActiveRecord::Base
    end
    
    #this table must have permission_id and role_id 
    class PermissionAssignment < ActiveRecord::Base
      belongs_to :permission
      belongs_to :role
    end
    
    class Role < ActiveRecord::Base
      has_many :users, :through => :role_assignments
      has_many :permissions, :through => :permission_assignments
    end
    
    #this table must have user_id and role_id     
    class RoleAssignment < ActiveRecord::Base
      belongs_to :role
      belongs_to :user
    end
    
    class User < ActiveRecord::Base
      has_many :roles, :through => :role_assignments
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多