简体   繁体   中英

Multiple has_many through relationships Rails

I'm still learning how to use has_many and has_many through relationships effectly. I am currently building a system where I would like users to be able to access certain maps that they are added to.

The map model is what I need the user to be able to access if they are apart of a certain group.

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

Since a user can belong to many groups I have a has_many through relationship

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

I thought about making a mapgroup model to take care of this but, so far, I am not so sure this is going to work.

class Mapgroup < ApplicationRecord
  belongs_to :map
  belongs_to :group
end

I am looking for a method to check to see what groups the user is apart of and then, based on those groups, give the user access to the corresponding maps. Am I on the right track with the relationships? How could I do this?

If you want to use MapGroup model only for keeping users an map connected ( ModelGroup has only foreign keys on Group and Map ) it's not the best approach. In this case it's better to opt for has_and_belongs_to_many assosiation. It will let you to assosiate Group s and Map s without creating useless model.

A has_and_belongs_to_many association creates a direct many-to-many connection with another model, with no intervening model.

class Group < ApplicationRecord
    ...
    has_and_belongs_to_many :maps
end

class Map < ApplicationRecord
    ...
    has_and_belongs_to_many :groups
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM