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
你原来的关联对我来说似乎没有多大意义。 @ org.users如何产生管理员用户(除非你的所有用户都是不太可能的管理员)?管理员似乎是组织和用户模型之间似乎是多对多的联合模型。 – Shreyas 2011-03-08 19:34:10
为什么不把用户的角色存储在一个字段中?有一个传统的管理类吗? – justinxreese 2011-03-08 20:11:39
工作正常(或者我认为?),因为:has_many:users,:through =>:admins - 当我打电话给用户时,它会加入管理员,然后加入用户。 – jmccartie 2011-03-08 20:26:38