Rails:使用 Devise 创建用户后,设置用户的配置文件



在使用design创建用户后,我想创建自动用户配置文件。

创建用户后,尝试在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

您应该了解Rails回调。

通过http://guides.rubyonrails.org/active_record_callbacks.html#creating-对象

解决方案是,将其添加到用户型号中

after_commit :create_default_profile, on: :create
private
def create_default_profile
self.create_profile!
# self.profile.new(pass_default_attrs).save!
end

最新更新