LoginSignup
1
1

More than 3 years have passed since last update.

Rails deviseの準備

Posted at

はじめに

Railsのdeviseの使い方を、何回かに分けてまとめます。
今回はdeviseの準備についてです。
最終的に、デフォルトのサインアップ画面とサインイン画面にアクセスできるようにします。

deviseの準備

gemのインストール

bundlerを事前にインストールしています。

GemFileに次の記述を追加します。

GemFile
gem 'devise'

ターミナルにて、次のコマンドを実行してgemをインストールします。

bundle install

deviseの設定ファイル

deviseの設定ファイル生成

ターミナルにて、次のコマンドを実行してdeviseの設定ファイルを生成します。

rails g devise:install

deviseの設定ファイル編集

設定ファイルのインストール後、ターミナルに次の文章が表示されます。

Some setup you must do manually if you haven't yet:

  1. Ensure you have defined default url options in your environments files. Here
     is an example of default_url_options appropriate for a development environment
     in config/environments/development.rb:

       config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

     In production, :host should be set to the actual host of your application.

  2. Ensure you have defined root_url to *something* in your config/routes.rb.
     For example:

       root to: "home#index"

  3. Ensure you have flash messages in app/views/layouts/application.html.erb.
     For example:

       <p class="notice"><%= notice %></p>
       <p class="alert"><%= alert %></p>

  4. You can copy Devise views (for customization) to your app by running:

       rails g devise:views

表示された文章の1〜4までの設定を行います。

1.デフォルトのURLを設定

環境ファイルにデフォルトのURLを設定します。

config/environments/development.rb
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

2.デフォルトのURLに対するルートを定義

1で設定したデフォルトのURLに対するアクションを定義します。
先にコントローラとビューを作成しておきます。
ターミナルにて、次のコマンドを実行します。

rails g controller Products index

デフォルトのURLに対するルートを定義します。

config/routes.rb
root 'products#index'
get 'products/index'

3.フラッシュメッセージの設定

フラッシュメッセージとは、ログイン成功時などに表示されるメッセージです。
「app/views/layouts/application.html.erb」内にフラッシュメッセージを設定します。
bodyタグの中に、指定されたpタグを2つ記述します。

app/views/layouts/application.html.erb
<body>
  <p class="notice"><%= notice %></p>
  <p class="alert"><%= alert %></p>

  <%= yield %>
</body>

4.deviseのカスタマイズ用のビューを生成

カスタマイズ用のビューを生成します。
デフォルトのビューを使用する場合、この作業は不要です。
ターミナルにて、次のコマンドを実行します。

rails g devise:views

モデルの生成

ログイン時に使用するモデルを生成します。
今回はUserというモデル名で生成します。
ターミナルにて、次のコマンドを実行します。

rails g devise User
rake db:migrate

実行すると、routes.rbに「devise_for :users」が追加されます。

config/routes.rb
devise_for :users
root 'products#index'
get 'products/index'

サインアップ画面、サインイン画面にアクセス

deviseの準備が正しくできているか確認します。

サインアップ画面

sign_up_000.png

サインイン画面

sign_in_000.png

サインアップ画面とサインイン画面が表示されたら、deviseの準備は完了となります。

おわりに

「rails g devise モデル名」を実行した後、routes.rbに「devise_for :モデル名」が追加されていなかったり、
「rails g devise:install」を実行したらターミナルが固まったりと色々ありました。

次はdeviseのカスタマイズをまとめようと思います。

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