0%

gem-devise-如何在註冊及更新user資料時增加欄位?

在使用devise這個gem的時候,雖然它已經幫我們預設做了很多事情,但總是有我們需要客製化的時候,這時候我們可以透過以下步驟來達到目的:

  1. 建立一個 migration,在table新增需要的欄位

    1
    2
    3
    4
    5
    6
    class AddColumnToUsers < ActiveRecord::Migration[6.0]
    def change
    add_column :users, :name, :string
    add_column :users, :birthday, :datetime
    end
    end
  2. rails db:migrate

  3. 確認schema.rb裡面已經加入欄位

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "name"
    t.datetime "birthday"
    t.string "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string "unconfirmed_email"
    t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
    end
  4. 參考devise官網的指示,讓新欄位的parameters允許通過並打開before_action的註解https://github.com/heartcombo/devise#strong-parameters

1
2
3
4
5
6
7
before_action :configure_sign_up_params, only: [:create]
before_action :configure_account_update_params, only: [:update]

def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
devise_parameter_sanitizer.permit(:account_update, keys: [:name])
end
  1. 最後回到頁面將新增欄位show出來