T. Cole
T. Cole

Reputation: 191

Administratively putting users into groups

There are many users and one administrator. Users can create groups and send/receive requests to join those groups. That system works fine. I am now building separate "super groups" that the admin creates. These "super groups" don't rely on requests, they rely on appointment. The admin selects a user, selects a group, and adds the chosen user into the chosen group. How do I accomplish this?

For example, as an admin, I would like to go to the user's profile page and on the profile page there is a drop-down(only admin-accessible) and add the user to the group of my choice. How would I accomplish this? Through a type of form? A boolean field? Could I just add an append method (<<) into my join model create action and have a select-tag for a group and then a create-submit button? I just need to be pointed in the general direction and I think that I can manage.

Of note: I am using a has_many :through association to capture the relationship. An admin has many "super groups" which are created/deleted fine. The "super group" has many members(users). I just need to know how to put users into a group administratively.

Upvotes: 0

Views: 312

Answers (1)

Jack Collins
Jack Collins

Reputation: 1165

UPDATE - What is the best practice for adding a user to a has_many :through association via dropdown?

You are talking about wanting to add a user to a super group FROM the user's profile page. This means you want to pass a super_group_id to the Rails controller, find that super group, and then add the user to that group.

This is one option:

 @user = User.find(params[:id]) # or user_id, depending on the controller
 @super_group = SuperGroup.find(params[:super_group_id])
 @super_group.users << @user

Original Answer:

How are you currently creating and deleting the Super Groups? I assume you have a SuperGroupsController. One way to accomplish this is to have a sub-controller SuperGroups::UsersController with your same RESTful actions (create, update, etc). Those restful actions handle the assigning/removing of the users to groups. This allows you to separate the checking that you need to do to make sure only an admin is taking these actions.

class SuperGroups::UsersController < ApplicationController
  before_action :verify_admin # create this method to do the checking

  def create
    # create a user super group association here
  end

  def delete
    # remove a user from the super group here
  end
end

This is apparently a best practice according to DHH. I first used this method after reading this article and I've found this pattern very clean and useful.

Upvotes: 1

Related Questions