Nerzid
Nerzid

Reputation: 467

Different Relationships with the same model

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;

  1. user_id in Group model which is to store owner of it is always nil although in GroupMap model it set's the user_id properly.
  2. In step 1, it is good to see owner in GroupMap too since its a member of that group too but its status is always nil. There are 3 type of status(waiting,accepted,reject). In this case, when a owner creates that group, its status with the group must be accepted as well.

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

Answers (1)

SteveTurczyn
SteveTurczyn

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

Related Questions