在用户新注册后再创建另一个模型 [英] Create another model upon user new registration in devise

查看:85
本文介绍了在用户新注册后再创建另一个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我的创建方法在 registrations_controller.rb 如下:

  class RegistrationsController< Devise ::注册控制器
def创建
超级
会话[:omniauth] = nil除非@ user.new_record?

#每个新用户自动创建一个默认配置文件
@profile = Profile.create
@ user.default_card = @ profile.id
@ user.save

end

但是,它不是创建一个新的配置文件,也不是字段对于@ user.default_card正在填写。如何在每个新用户注册设计时自动创建一个新的配置文件?

解决方案

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

您的代码不工作的一个可能原因是 @profile = Profile.create 未成功执行,因为它是失败的验证或某事。这将导致 @ profile.id 正在 nil ,因此 @ user.default_card nil



以下是我将如何实现:

  class User< ActiveRecord :: Base 

...

before_create:create_profile

def create_profile
profile = Profile.create
self .default_card = profile.id
#也许检查个人资料是否被创建并引发错误
#或提供某种错误处理
end
end

在您的代码(或我的)中,您可以随时放一个简单的 puts 以检查新配置文件是否正在创建。即 puts(@profile = Profile.create)


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.

My create method in the registrations_controller.rb is as follows:

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

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?

解决方案

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.

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆