2017-03-01 11 views
0

私は3つのモデルを持っています。 ユーザ,グループおよびグループマップ同じモデルとの関係が異なる

ユーザーは複数のグループと複数のユーザーを持つことができます。これはn-m関係であり、GroupMapを介して行われます。 GroupMapにはステータスとタイプもありますので、このモデルも必要です。これが最初の関係です。

グループに所属するユーザーは、1人のユーザーのみです。これは1-nの関係です。

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 

私は2つの問題がここにあります。このコードでグループを作成することもできますが、

  1. user_idは、GroupMapモデルではuser_idが正しく設定されていますが、所有者を格納するグループモデルでは常にnilです。
  2. ステップ1では、グループのメンバーであるGroupMapでも所有者が表示されますが、そのステータスは常にnilです。ステータスには3種類あります(待機、承諾、拒否)。この場合、所有者がそのグループを作成するときには、そのグループのステータスも受け入れなければなりません。

ログ

(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]] 

答えて

1

グループ/ユーザの所有関係を通じてGroupMap関係とは別の関係です。別々に指定する必要があります。

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 
+0

ご質問ありがとうございます。質問2について私は何ができますか? – Nerzid

+0

このグループのgroup_mapステータスを「受け入れられる」ように設定する方法を示すために私の答えを編集しました。 – SteveTurczyn

関連する問題