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

时间:2011-03-08 19:29:00

标签: ruby-on-rails polymorphic-associations

现有型号:

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

从技术上讲,这是有效的,但我不能让我的用户离开这个。我试图在Moderator表中添加user_id列,但没有关联,Rails不想抓住它:

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

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

更新

结束了这一点(注意:主持人被称为“网络用户”):

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

2 个答案:

答案 0 :(得分: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,它将加入组织和角色(例如管理员或主持人)。这样,当有人出现并宣布组织必须有秘书,网站管理员或其他什么时,您不必修改所有现有模型。

答案 1 :(得分:0)

我不确定我是否理解你在这里所做的事情但是...它在我看来就像你想要的那样:

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