在Devise用户新注册时创建另一个模型

4
我正在使用devise进行新用户注册。在创建新用户之后,我还希望为该用户创建个人资料。
我的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字段也没有被填充。我该如何在每次使用devise进行新用户注册时自动创建一个新的个人资料?

2个回答

6
我会把这个功能放到用户模型的before_create回调函数中,因为它本质上是模型逻辑,不需要额外的保存调用,而且更加优雅。
你的代码无法正常工作的一个可能原因是@profile = Profile.create没有成功执行,因为它未通过验证或其他原因失败。这将导致@profile.idnil,因此@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

在你的代码(或者我的)中,你总是可以放一个简单的 puts 语句来检查新的个人资料是否已被创建。例如 puts (@profile = Profile.create)


谢谢!你说得对,我在Profile模型上有验证,这导致我无法创建个人资料。非常感谢!现在我可以在每次新用户注册时自动创建新的个人资料了。你有什么想法,如何在创建后下一次编辑个人资料时调用验证? - Sayanee
好的,我弄清楚了,在验证中,你只能在特定的操作上进行验证。问题解决了,谢谢 :) http://guides.rubyonrails.org/active_record_validations_callbacks.html#on - Sayanee

0

类似的另一种方法是这样的(使用build_profile方法):

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :async,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable, omniauth_providers: [:facebook]


  has_one :profile

  before_create :build_default_profile

  private
  def build_default_profile
    # build default profile instance. Will use default params.
    # The foreign key to the owning User model is set automatically
    build_profile
    true # Always return true in callbacks as the normal 'continue' state
    # Assumes that the default_profile can **always** be created.
    # or
    # Check the validation of the profile. If it is not valid, then
    # return false from the callback. Best to use a before_validation
    # if doing this. View code should check the errors of the child.
    # Or add the child's errors to the User model's error array of the :base
    # error item
  end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接