gpt4 book ai didi

ruby-on-rails - 在用户新注册时创建另一个模型

转载 作者:行者123 更新时间:2023-12-04 05:49:14 25 4
gpt4 key购买 nike

我正在使用 devise进行新用户注册。创建新用户后,我还想为该用户创建一个配置文件。

我的 create registrations_controller.rb 中的方法如下:

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 的字段。如何在每个新用户注册设备时自动创建一个新的配置文件?

最佳答案

我会将此功能放入 before_create用户模型上的回调函数,因为它本质上是模型逻辑,只会不添加另一个保存调用,而且通常更优雅。

您的代码不起作用的一个可能原因是 @profile = Profile.create未成功执行,因为它未通过验证或其他原因。这将导致 @profile.id正在 nil因此 @user.default_cardnil .

这是我将如何实现这一点:

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)

关于ruby-on-rails - 在用户新注册时创建另一个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8337682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com