2013-10-10 110 views
2

因此,基本上我已經編寫了自己的身份驗證,而不是使用gem,因此我可以訪問控制器。我的用戶創建工作正常,但是當我的用戶創建時,我還想在我的個人資料模型中爲他們創建個人資料記錄。我主要工作,我似乎不能將新用戶的ID傳遞到新的profile.user_id中。這是我在用戶模型中創建用戶的代碼。Ruby on Rails - 在創建用戶時創建配置文件

def create 
    @user = User.new(user_params) 
    if @user.save 
     @profile = Profile.create 
     profile.user_id = @user.id 
     redirect_to root_url, :notice => "You have succesfully signed up!" 
    else 
     render "new" 
    end 

的配置文件創建它只是不添加來自新創建的用戶爲user_id。如果有人可以幫助它,將不勝感激。

回答

11

你真的應該這樣做,因爲在用戶模式的回調:

User 
    after_create :build_profile 

    def build_profile 
    Profile.create(user: self) # Associations must be defined correctly for this syntax, avoids using ID's directly. 
    end 
end 

現在,這總是會創建一個新創建的用戶配置文件。

你的控制器,然後被簡化爲:

def create 
    @user = User.new(user_params) 
    if @user.save 
    redirect_to root_url, :notice => "You have succesfully signed up!" 
    else 
    render "new" 
    end 
end 
+0

這個好主意。我想你的建議將會是_User has_one Profile_。對?我需要創建一個配置文件控制器嗎? –

0

您這裏有兩個誤區:

@profile = Profile.create 
profile.user_id = @user.id 

第二行應該是:

@profile.user_id = @user.id 

第一行創建的形象和你沒有的分配後「再節約」 user_id

更改這些行這樣的:

@profile = Profile.create(user_id: @user.id) 
+0

我可以添加額外的字段,像profile.email = user.email –

9

這是現在在Rails中更容易4.

你只需要下面一行添加到您的用戶模型:

after_create :create_profile 

並觀察軌道如何自動爲用戶創建配置文件。

+1

啊!甜..... 1 –

+1

其真棒... :) –

+1

好提示...... – hguzman