我对Ruby on Rails中的关联有疑问。在应用程序中有项目,用户,角色和组。该项目属于具有用户的组,用户可以属于许多不同的组,但在该组中只能有一个特定的角色。例如:
在一个组中,用户是项目所有者,但在另一个组中,他是作家。
使用Rails中的内置函数实现此目的的最佳方法是什么?
由于
答案 0 :(得分:8)
这是一套非常快速的模型,可以满足您的要求:
class User < ActiveRecord::Base
has_many :group_memberships
has_many :groups, :through => :group_memberships
end
class GroupMembership < ActiveRecord::Base
belongs_to :user
belongs_to :role
belongs_to :group
end
class Role < ActiveRecord::Base
has_many :group_memberships
end
class Group < ActiveRecord::Base
has_many :group_memberships
has_many :users, :through > :group_memberships
end
基本上有一个连接表,其中包含用户,组和角色ID。我会将迁移作为提问者的练习