Reputation: 1065
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).
Upvotes: 4
Views: 1589
Reputation: 10497
I'll move set_membership
to Group
model (active_create
is a model callback, so it will not work in a controller), and create the Membership
there, like this:
class Group < ApplicationRecord
after_create: set_membership
belongs_to :creator, class_name: "User"
has_many :memberships
has_many :users, through: :memberships
private
def set_membership
Membership.create!(user_id: user_id, group_id: id)
end
end
Upvotes: 5