Rails after_create callback to update a different model

Viewed 945

I have users, groups, and memberships. I have a has_many through relationship set up between users and groups using the membership join table. What I am trying to do is set up an after_create callback that adds a new record into the memberships table whenever a user creates a new group, that way the creator is automatically a member of the group.

Right now, a user can create a group, but the group will display having 0 members, and the user will have to join the group. How can I automate that part with the callback if I'm trying to update the membership Model from the Group controller?

user.rb

class User < ApplicationRecord
  has_many :created_groups, class_name: "Group"
  has_many :memberships
  has_many :groups, through: :memberships
end

group.rb

class Group < ApplicationRecord 
  belongs_to :creator, class_name: "User"
  has_many :memberships
  has_many :users, through: :memberships
end

membership.rb

class Membership < ApplicationRecord
  belongs_to :user
  belongs_to :group
end

groups_controller.rb

class GroupsController < ApplicationController
  after_create :set_membership

  def create
    @group = current_user.groups.build(group_params)

    respond_to do |format|
      if @group.save
        format.html { redirect_to @group, notice: 'You have a new Group!' }
      else
        format.html { render :new }
      end
    end
  end

  private
    def set_membership
    end
end

The set_membership part is where I'm completely lost. I just need to grab the created group's id and use it to create a new membership (with current user id).

1 Answers
Related