Triple join in Ruby on Rails

ⅰ亾dé卋堺 提交于 2019-12-12 10:56:57

问题


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.

What is the best way to implement this using the built in functions in Rails?

Thanks


回答1:


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

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



来源:https://stackoverflow.com/questions/636296/triple-join-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!