【发布时间】:2012-03-22 07:19:48
【问题描述】:
我已经建立了一个基于角色的访问控制系统,具有以下模型:
- 角色(作为 STI),
- UserRole(全局角色)
- ProjectRole(项目特定角色)
- 分配(具有不同资源的多态)
- 用户
- 项目(作为分配的一种资源类型)
只有拥有特定 UserRole 的用户才能对项目负责。 此用户角色名为“负责项目”,ID 为 2。
在用户模型中有两个has_many关联:responsible_assignments和responsible_projects。 仅当用户具有 ID 为 2 的 UserRole“负责项目”时,此关联才有效。
是否可以在用户模型中为责任_* 关联创建条件关联,这是建立这种关系的常用方法吗?
解决此类问题的最佳做法是什么?
class Role < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments
class UserRole < Role
class ProjectRole < Role
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
belongs_to :resource, :polymorphic => true
class User < ActiveRecord::Base
has_many :assignments
has_many :roles, :through => :assignments,
:class_name => "UserRole"
has_many :responsible_assignments, :class_name => "Assignment",
:conditions => { :role_id => 4 } // specific project role
has_many :responsible_projects, :through => :responsible_assignments,
:source => :resource,
:source_type => 'Project',
:conditions => { :status => 1 } // project is active
...
class Project < ActiveRecord
...
【问题讨论】:
-
条件关联是什么意思?有什么条件?
-
条件是:如果用户没有id为2的角色,则责任_*关联无效/不应设置。
标签: ruby-on-rails conditional has-many polymorphic-associations single-table-inheritance