9

我已经建立了基于角色的访问控制研究体系有如下型号:是否可以在模型中创建条件关联?

  • 角色(如STI),
    • 的UserRole(全球角色)
    • ProjectRole(项目特定的角色)
  • 作业(使用不同资源的多态性)
  • 用户
  • Proj ect(作为分配的一种资源类型)

如果用户具有特定的UserRole,则只允许他们对项目负责。 此Userrole名称为“负责项目”并具有ID 2.

在用户模型中,有两个has_many关联:responsible_assignments和responsible_projects。 此关联仅在用户具有ID为2的UserRole“负责项目”的情况下有效。

是否可以在用户模型中为responsible_ *关联创建条件关联,并且这是设置此类常用方法关系?

什么是解决这类问题的最佳做法?

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 
    ... 
+0

你是什么意思由条件协会做?什么条件? – Yanhao 2012-03-07 14:22:22

+0

的条件是:如果用户没有ID为2的作用,responsible_ *协会是无效的/不应该设置。 – tonymarschall 2012-03-07 15:11:54

回答

7

你不能把在协会这样的条件。这些东西在范围内处理。

阅读http://guides.rubyonrails.org/active_record_querying.html#scopes以获取更多信息。

例如,对于你的情况,

你想要一个用户下的所有任务(IDS)与特定项目角色

scope :responsible_users, where('users.role_id = 4') 
scope :select_assignment_ids, select('assignments.id') 
scope :responsible_assignments, joins(:assignments).responsible_users.select_assignment_ids 

你希望所有项目(IDS),用户在与特定项目角色,这些都是积极的。

scope :active_projects, where('projects.status = 1') 
scope :select_project_ids, select('projects.id') 
scope :responsible_projects, joins(:assignments => :projects).responsible_users.active_projects.select_project_ids 
1

这些关联是在加载模型时创建的。您的情况在当时是未知的。 只能包括中消协的条件来过滤掉不需要的记录。

相关问题