Rails:使用Devise创建用户后,设置用户个人资料

时间:2018-07-18 11:11:15

标签: ruby-on-rails ruby

使用devise创建用户后,我要创建自动用户个人资料。

创建尝试在Rails控制台上使用User.last.profile的用户后

  User Load (0.4ms)  SELECT  `users`.* FROM `users` ORDER BY `users`.`id` DESC LIMIT 1
  Profile Load (0.3ms)  SELECT  `profiles`.* FROM `profiles` WHERE `profiles`.`user_id` = 3 LIMIT 1
=> nil


class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  has_one :profile
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

class Profile < ApplicationRecord
  belongs_to :user
end

class CreateProfiles < ActiveRecord::Migration[5.2]
  def change
    create_table :profiles do |t|
      t.integer :user_id
      t.integer :cash, null: false, default: "0"

      t.timestamps
    end
  end
end

1 个答案:

答案 0 :(得分:0)

您应该查看Rails回调。

通过 http://guides.rubyonrails.org/active_record_callbacks.html#creating-an-object

解决方案是,将其添加到 user 模型

after_commit :create_default_profile, on: :create

private

def create_default_profile
  self.create_profile!
  # self.profile.new(pass_default_attrs).save!
end