RailsでmySQLを使ってgem:deviseを実装する


こんにちは

Railsでポートフォリオを作るときに、mySQLを使ってさらにdeviseを導入してログインなどのシステムを導入したい

そんな人たちに、自分が使ったやり方を自分の復習も込めて書きます。

まずは、データベースにmySQLを使っている、railsプロジェクトを作る

$rails new プロジェクト名 -d mysql

造られたプロジェクトのgemfileに

gem 'devise'

を記述する。

ここまで書いたら、下記のコマンドを実行して、gemファイルを読み込みます。

$bundle install

まずはここまでで一セット。そして、間髪入れず第二セットいきます。

gem:deviseの関係ファイルをプロジェクトに作ります。このとき、先ほどの作ったrailsプロジェクトのフォルダに移動しておいてください。

$ rails generate devise:install

上記のコマンドを実行すると下記のような文章が出てきます。

===============================================================================
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:

    <%= notice %>


    <%= alert %>

  4. If you are deploying on Heroku with Rails 3.2 only, you may want to set:

    config.assets.initialize_on_precompile = false

    On config/application.rb forcing your application to not access the DB
    or load models when precompiling your assets.

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

    rails g devise:views

===============================================================================

上から順に説明すると

1、config/environments/development.rbにconfig.action_mailer.default_url_options = { host: 'localhost', port: 3000 }を記述してくれよな

2、config/routes.rbにroot to: "home#index"を記述してくれよな

3、app/views/layouts/application.html.erbに
    

<%= notice %>


<%= alert %>


を追記してくれよな

4,使っているRailsのバージョンが3.2だったらconfig/application.rbに
 config.assets.initialize_on_precompile = falseを記述してくれよな
(Railsのバージョンはrails -vでわかる)

5,deviseにデフォルトで設定されている画面(view)をカスタマイズしたい時は、
 rails g devise:views
 を実行すると変更を加えるためのviewファイルを作成するぞ

という意味です。

これで、第二セットは終わり。ラストにデータベースを作って終わります。

mySQLを

$sudo service mysqld start

で立ち上げてから

下記のコマンドでデータベースを作る

rake db:create

そして、モデル(今回はUserモデルを作る)

$ rails g devise user

gem 'devise'のおかげでemailとpasswordはこのコマンドを使うと自動で追加されるらしい

追加したいカラムは都度追加すれば良い

また、このままではコントローラーがdeviseになっているため

userコントローラーで操作できるようにするため、下記のソースをroute.rbに記述する

devise_for :users, controllers: {
registrations: 'users/registrations',
sessions: 'users/sessions',
passwords: 'users/passwords'
}

その後、userコントローラーを作る,

認証ユーザーのモデルが User であれば、app/controllers/users ディレクトリ以下にファイル作成

$rails g devise:controllers users

そして、この設定をデータベースに反映させる

rake db:migrate

以上です。