三人在Ruby中加入on Rails的 [英] Triple join in Ruby on Rails
问题描述
我有一个关于Ruby on Rails中的关联问题。在应用有项目,用户,角色和组。该项目属于与用户的组,用户可以属于多个不同的组,但只能有该组中的一个具体的作用。例如:
I have question regarding associations in Ruby on Rails. In the application there are projects, users, roles and groups. The project belongs to a group with users, a user can belong to many different groups but can only have one specific role within that group. For example:
在一组用户是项目业主,但在另外一组,他是一个作家。
In one group the user is the project owner, but in another group he is a writer.
什么是实现这个使用内置的功能在Rails中的最佳方式是什么?
What is the best way to implement this using the built in functions in Rails?
感谢
推荐答案
下面是一个非常快的一套模式,可以满足您的需要:
Here is a very quick set of models that should fulfill your requirements:
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在它连接表。我会离开的迁移作为练习提问
Basically there is a join table that has a user, group and role id in it. I'll leave the migrations as an exercise for the questioner
这篇关于三人在Ruby中加入on Rails的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!