All threads / Creating usergroups

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Creating usergroups

Trenton Tyler asked in Rails

I am creating an application where users can belong to groups and those groups can belong to a map.

In order to link a user and group together I created a model called usergroup. I listed the models below so you can see the associations.

class Usergroup < ApplicationRecord
  belongs_to :user, optional: true
  belongs_to :group, optional: true
end
class Group < ApplicationRecord
  has_many :usergroups
  has_many :users, through: :usergroups
end
class User < ApplicationRecord
  has_many :usergroups
  has_many :groups, through: :usergroups
end

I will be needing an association between my Group and Map so that, when a map is added to a group, all users in the usergroup with that map_id will be able to access that map. My question is - is there a more practical way to achieve this? At the moment I have a SO question regarding the same topic and have not gotten a response even with a bounty set. I was hoping to get some input on here. Any ideas?

Thanks - https://stackoverflow.com/questions/47985654/rails-auto-complete-user-object

Hey Trenton,

What you've got is definitely on the right track. The reason being that to create these many to many relationships in SQL is that you have to have the join table in order to have them.

It sounds like you might actually want to put the belongs_to :map on the Group itself so that you can easily add all the group's users to a map.

Also left you a comment on your SO post. 👍

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 34,674+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.