0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

devise nameカラム追加

Last updated at Posted at 2023-06-04

ゴール

nameカラムが追加された状態でdevise導入

背景

deviseを導入する時毎回「devise nameカラム」でググるので、覚える為に書きました。

手順

1、gemインストール

Gemfile
gem 'devise'

$ bundle

2、初期ファイル、Userモデル、viewファイル作成

$ rails g devise:install

$ rails g devise user

$ rails g devise:views

3、マイグレーションファイルを編集して、nameカラムを追加する

db/migrate/〇〇_devise_create_users.rb
# frozen_string_literal: true

class DeviseCreateUsers < ActiveRecord::Migration[7.0]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :name,              null: false, default: "" #追加
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

  ~省略~

  end
end

$ rails db:migrate

4、新規ユーザー登録画面のフォームにname欄を追加

app/views/devise/registrations/new.html.erb
<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= render "devise/shared/error_messages", resource: resource %>

  <div class="field"> #追加
    <%= f.label :name %><br />
    <%= f.text_field :name, autofocus: true %>
  </div>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
  </div>
  
  ~省略~

  end
end

5、パラメーターの許可

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller? #追加

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
  end
end

以上です。

おまけ

・画面にログイン、ログアウト、新規登録リンクを表示

app/views/layouts/application.html.erb
  <header>
    <ul class="menu menu-vertical lg:menu-horizontal bg-base-100 rounded-box">
      <li><%= link_to "ログイン", new_user_session_path %></li>
      <li><%= link_to "ログアウト", destroy_user_session_path, data: { turbo_method: :delete } %></li>
      <li><%= link_to "新規登録", new_user_registration_path %></li>
    </ul>
  </header>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?