2011-03-08 148 views
0

现有型号:Rails:拥有管理员和管理员以及用户的组织

class Organization < ActiveRecord::Base 
 has_many :admins 
 has_many :users, :through => :admins 

class User < ActiveRecord::Base 
 has_many :admins 
 has_many :organizations, :through => :admins 

无汗。 @org.users返回管理员用户列表。

现在我需要添加另一个角色:版主。我不能在中间添加另一个表(因为一个关联只能有一个目标)。

一位朋友建议我让版主多态。我在Rails指南中读到了这一点,但不知道如何在这里实现它。

我试过这个:

class Moderator < ActiveRecord::Base 
    belongs_to :modable, :polymorphic => true 
end 

...然后将其添加到我的用户和组织模型:

has_many :moderators, :as => :modable 

从技术上讲这可行,但是,我无法让我的用户这个的。我试图在主持人表中添加一个user_id列,但没有关联,Rails不想抓住它:

> @org.moderators.joins(:users) 
ActiveRecord::ConfigurationError: Association named 'users' was not found; perhaps you misspelled it? 

任何帮助都非常感谢。谢谢!

UPDATE

结束于此(注意:主持人被称为“网络用户”):

class Organization < ActiveRecord::Base 
    has_many :roles 
    has_many :users, :through => :roles 

    has_many :admin_roles, :conditions => {:role_type => "AdminRole"} 
    has_many :admins, :through => :admin_roles, :source => "user", :class_name => 'User' 

    has_many :network_user_roles, :conditions => {:role_type => "NetworkUserRole"} 
    has_many :network_users, :through => :network_user_roles, :source => "user", :class_name => 'User' 

# This all lives in one table; it has a organization_id, user_id, and special_role_type columns 
class Role 
 belongs_to :organization 
 belongs_to :user 
end 

class AdminRole < Role 
end 

class NetworkUserRole < Role 
end 

class UserRole < Role 
end 
+0

你原来的关联对我来说似乎没有多大意义。 @ org.users如何产生管理员用户(除非你的所有用户都是不太可能的管理员)?管理员似乎是组织和用户模型之间似乎是多对多的联合模型。 – Shreyas 2011-03-08 19:34:10

+0

为什么不把用户的角色存储在一个字段中?有一个传统的管理类吗? – justinxreese 2011-03-08 20:11:39

+0

工作正常(或者我认为?),因为:has_many:users,:through =>:admins - 当我打电话给用户时,它会加入管理员,然后加入用户。 – jmccartie 2011-03-08 20:26:38

回答

0

我不知道我知道你在这里做什么,但。 ..它看起来像你对我会想:

class Organization < ActiveRecord::Base 
    has_many :users 
    has_many :admins, :through => :users 
    has_many :moderators, :through => :users 
1

我认为你正在寻找的东西更像

class Organization < ActiveRecord::Base 
    has_many :users 
    has_many :admins 
    has_many :moderators 
    has_many :admin_users, :through => :admins, :class_name=>"User" 
    has_many :moderator_users, :through => :admins, :class_name=>"User" 

class Admin < ActiveRecord::Base 
    has_many :organizations 
    belongs_to :user 

class Moderator < ActiveRecord::Base 
    has_many :organizations 
    belongs_to :user 

class User < ActiveRecord::Base 
    has_many :organizations 
    has_many :admins 
    has_many :moderators 

基本上,管理员不是组织和用户之间的桥梁(反之亦然)没有意义。一个组织拥有管理员,一个组织拥有用户,一个组织拥有主持人。当用户拥有管理员(在某些用户是管理员的意义上)时,用户与组织的关系不应该通过管理员,尤其是对于不是管理员的用户。

我认为更好的方法是添加一个新模型,如OrganizationRole,它将加入组织和角色(如管理员或主持人)。这样,当有人出现并宣布组织必须有秘书或网站管理员或其他人时,您不必修改所有现有模型。

相关问题