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

【Rails】deviseの導入 基礎

Posted at

Railsアプリにて、ユーザー管理機能のためのgemである、
「devise」を導入する基本の手順を
備忘録も兼ねてご紹介。

1. Gemfile に devise を追加

最下行に記載。

Gemfile
gem 'devise'

bundle instrallを実行する。

2. devise を適用させる

ターミナル
rails g devise:install

3. devise仕様の Userモデルを作成

通常のモデル作成用コマンドとは違って、devise専用のコマンドで、
Userモデルを作成します。

ターミナル
rails g devise user

実行後、ルーティングに「devise_for :users」と追記され、
ログインと新規登録で必要なルーティングが生成されるようです。

◉ 続けて実行します。

ターミナル
rails db:migrate

4. 新規登録・ログインできるようにする

ヘッダー等に「新規登録」「ログイン」できるボタンを作る。
user_signed_in? メソッドにより、未ログイン時はログイン時と違う表示になります。

sample.haml
.header
  .header__user-btn
    - if user_signed_in?
      = link_to "新規投稿", new_post_path, class: "btn"
      = link_to "ログアウト", destroy_user_session_path, method: :delete, class: "btn"
    - else
      = link_to "ログイン", new_user_session_path, class: "btn"
      = link_to "新規登録", new_user_registration_path, class: "btn"

devise用のビューを作る

実際に登録やログイン情報を入力する画面を表示させます。

rails g devise:views

ここまでで、登録→ログイン→ログアウトまで実装できています。
※メールアドレスは無効な物でも使用できる状態です。


以上で終了です。
ご覧いただきありがとうございました。

1
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
1
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?