多个has_many通过关系Rails

时间:2017-12-03 20:40:21

标签: ruby-on-rails

我还在学习如何通过关系有效地使用has_many和has_many。我目前正在构建一个系统,我希望用户能够访问它们被添加到的某些maps

地图模型是我需要用户能够访问的,如果他们是特定群体的一部分。

class Map < ApplicationRecord
  has_many :rows
  has_many :mapgroups
  has_many :groups, through: :mapgroups
end

由于用户可以属于多个组,因此我有一个has_many通过关系

class Usergroup < ApplicationRecord
  belongs_to :user
  belongs_to :group
end


class User < ApplicationRecord
  has_many :usergroups
  has_many :groups, through: :usergroups
end


class Group < ApplicationRecord
  has_many :usergroups
  has_many :users, through: :usergroups
  has_many :mapgroups
  has_many :maps, through: :mapgroups
end

我考虑制作一个地图组模型来处理这个问题,但到目前为止,我还不确定这是否会起作用。

class Mapgroup < ApplicationRecord
  belongs_to :map
  belongs_to :group
end

我正在寻找一种方法来检查用户所属的组,然后根据这些组,让用户访问相应的地图。我与关系走在正确的轨道上吗?我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

如果您想仅使用MapGroup模型 来保持用户与地图的关联(ModelGroup只有Group上的外键和Map )这不是最好的方法。在这种情况下,最好选择has_and_belongs_to_many协商。它可以让您在不创建无用模型的情况下分析GroupMap

  

has_and_belongs_to_many关联创建与另一个模型的直接多对多连接,没有中间模型。

class Group < ApplicationRecord
    ...
    has_and_belongs_to_many :maps
end

class Map < ApplicationRecord
    ...
    has_and_belongs_to_many :groups
end
相关问题