在用户新注册时创建另一个模型 [英] Create another model upon user new registration in devise
问题描述
我正在使用 devise 进行新用户注册.创建新用户后,我还想为该用户创建一个配置文件.
I'm using devise to do the new user registration. Right after a new user is created, I would also like to create a profile for that user.
我在registrations_controller.rb
中的create
方法如下:
class RegistrationsController < Devise::RegistrationsController
def create
super
session[:omniauth] = nil unless @user.new_record?
# Every new user creates a default Profile automatically
@profile = Profile.create
@user.default_card = @profile.id
@user.save
end
但是,它不会创建新的个人资料,也不会填写@user.default_card 的字段.如何在每个新用户注册设备时自动创建新的个人资料?
But, it is not creating a new Profile and neither is the field for @user.default_card is being filled in. How can I create a new Profile automatically upon each new user registration with devise?
推荐答案
我会将此功能放入用户模型上的 before_create
回调函数中,因为它本质上是模型逻辑,只是不会添加另一个保存调用并且通常更优雅.
I would put this functionality into an before_create
callback function on the user model since it is essentially model logic, would only not add another save call and is just generally more elegant.
您的代码不工作的一个可能原因是 @profile = Profile.create
没有成功执行,因为它没有通过验证或其他原因.这将导致 @profile.id
为 nil
,因此 @user.default_card
为 nil
.
One possible reason why your code is not working is that @profile = Profile.create
is not executed successfully because it is failing validations or something. This would result in @profile.id
being nil
and thus @user.default_card
is nil
.
这是我将如何实现这一点:
Here is how I would implement this:
class User < ActiveRecord::Base
...
before_create :create_profile
def create_profile
profile = Profile.create
self.default_card = profile.id
# Maybe check if profile gets created and raise an error
# or provide some kind of error handling
end
end
在您的代码(或我的)中,您始终可以放置一个简单的 puts
来检查是否正在创建新配置文件.即 puts (@profile = Profile.create)
In your code(or mine), you can always put a simple puts
to check if the new profile is getting created. i.e. puts (@profile = Profile.create)
这篇关于在用户新注册时创建另一个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!