2017-03-01 62 views
0

我有3個模型; 用戶,組地圖與同一模型的不同關係

用戶可以有多個組和多個用戶組。這是n-m關係,它通過GroupMap完成。 GroupMap也有狀態和類型,所以我也需要這個模型。這是第一個關係。

一個組只能有一個是用戶的所有者。這是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在要存儲所有者的組模型中,user_id始終爲nil,儘管在GroupMap模型中它正確地設置了user_id。
  2. 在第1步中,最好還是在GroupMap中看到所有者,因爲它也是該組的成員,但其狀態始終爲零。有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

謝謝你,問題1的作品。我能做些什麼關於問題2? – Nerzid

+0

我編輯了我的答案,以顯示如何將此組的group_map狀態設置爲「接受」 – SteveTurczyn