2017-10-16 46 views
0

我正在嘗試創建新用戶註冊時的資源Mission。 Mission也有一個外鍵Location當用戶註冊時從模型創建資源

class User < ApplicationRecord 
    after_create :create_mission 

    private 
    def create_mission 
    Mission.create(user: self, location_id: 1, name: 'Mission 1') 
    end 
end 

但是這段代碼不起作用。我該如何解決它?

回答

1

如何:

class User < ApplicationRecord 
    after_create :create_mission 

    private 
    def create_mission 
    missions.create! location_id: 1, name: 'Mission 1' 
    end 
end 

現在你的錯誤可能是與create!可見。嘗試這個。

1

我不建議你在回調中建立關係。如果您需要在其他操作或控制檯中創建用戶,它將會傷害您。最好在控制器創建創建後(在未來的某個服務對象)

def create 
    if @user.save 
    @user.missions.create(...) 
    end 
end 

你也可以使用調試器來檢查錯誤動態(隨軌道https://github.com/deivid-rodriguez/byebug,只需要插入代碼中的「調試」),可能你有一些驗證錯誤。

相關問題