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 3 years have passed since last update.

rails devise導入からflash設定まで 備忘録

Posted at

🔳deviseを使ったユーザー機能実装
devise userでモデルを作成する

rails g devise user

マイグレーションファイルを編集する

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

    add_index :users, :name, unique: true

rails db:migrateする。

モデルにバリデーションを追加する

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

  validates :name, presence: true, uniqueness: true

end

間違えたらrails db:rollback

application_controoler.rbを編集

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :authenticate_user!
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

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

簡単に説明すると、サインアップ時に入力されたnameキーの内容の保存を許可

ログインビュー画面を編集(下記は例)

#account-page.account-page
  .account-page__inner.clearfix
    .account-page__inner--left.account-page__header
      %h2 Edit Account
      %h5 アカウントの編集
      = link_to "ログアウト", '#', class: 'btn'
      = link_to "トップページに戻る", :back, class: 'btn'
    .account-page__inner--right.user-form
      = form_for(current_user) do |f|
        .field
          .field-label
            = f.label :name
          .field-input
            = f.text_field :name, autofocus: true
        .field
          .field-label
            = f.label :email
          .field-input
            = f.email_field :email
        .actions
          = f.submit "Update", class: 'btn'

routesを設定
コントローラを編集

  def edit
  end

  def update
    if current_user.update(user_params)
      redirect_to root_path
    else
      render :edit
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :email)
  end

フラッシュにビューを追加
#app/views/layouts/_notifications.html.haml

.notification
  - flash.each do |key, value|
    = content_tag :div, value, class: key

#app/views/layouts/application.html.haml

  %body
    = render 'layouts/notifications'
    = yield
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?