簡體   English   中英

Rails:使用Devise創建用戶后,設置用戶個人資料

[英]Rails: after creating user with Devise, set user's profile

用devise創建用戶后,我想創建自動User的個人資料。

創建用戶后嘗試在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-an-object

解決方案是,在用戶模型中添加

after_commit :create_default_profile, on: :create

private

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM