Reputation: 467
I've 3 models; User , Group and GroupMap.
Users can have multiple groups and groups have multiple users. This is n-m relationship and it is done via GroupMap. GroupMap also have status, and type so I need this model as well. This is the first relationship.
A group can only have one owner which is user. this is 1-n relationship.
user.rb
class User < ApplicationRecord
has_many :group_maps
has_many :groups, :through => :group_maps
group.rb
class Group < ApplicationRecord
belongs_to :user
has_many :group_maps
has_many :users, :through => :group_maps
group_map.rb
class GroupMap < ApplicationRecord
belongs_to :group
belongs_to :user
groups_controller.rb
class GroupsController < ApplicationController
def new
@group = Group.new
end
def create
@group = current_user.groups.create(group_params)
if @group.save
redirect_to root_path
else
render 'new'
end
end
Although I can create groups with this code there are 2 problems here;
log
(0.0ms) begin transaction
SQL (1.0ms) INSERT INTO "groups" ("name") VALUES (?) [["name", "Football lovers"]]
SQL (0.5ms) INSERT INTO "group_maps" ("group_id", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["group_id", 8], ["user_id", 4], ["created_at", 2017-03-01 19:03:55 UTC], ["updated_at", 2017-03-01 19:03:55 UTC]]
Upvotes: 0
Views: 51
Reputation: 36860
The group / user owner relationship is a separate relationship than the through GroupMap
relationship. You need to specify it separately.
def create
@group = current_user.groups.create(group_params)
@group.user = current_user
if @group.save
group_map = @group.group_maps.first
group_map.status = 'accepted'
group_map.save
redirect_to root_path
else
render 'new'
end
end
Upvotes: 1