用户在设计中进行新注册时创建另一个模型

Say*_*nee 4 ruby-on-rails devise ruby-on-rails-3

我正在使用设计来进行新的用户注册.在创建新用户之后,我还想为该用户创建配置文件.

我的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
Run Code Online (Sandbox Code Playgroud)

但是,它没有创建新的配置文件,也没有填写@ user.default_card的字段.如何在每个新用户注册时自动创建新的配置文件?

cmp*_*lis 6

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

您的代码无法正常工作的一个可能原因是,@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
    # Maybe check if profile gets created and raise an error 
    #  or provide some kind of error handling
  end
end
Run Code Online (Sandbox Code Playgroud)

在您的代码(或我的代码)中,您总是可以轻松puts检查新配置文件是否已创建.即puts (@profile = Profile.create)