deviseを使ってログイン処理をしてみる。
ログイン処理を作るのでdeviseのメモ。
Deep valley まとめ版 - RailsでDeviseを使ってみたを参考にやってみる。
環境: Ubuntu11.10, RVM1.13.4, Rails3.2.3
1. deviseをインストールする
% rvmsudo gem install devise
2. 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: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 Rails 3.1 on Heroku, 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.===============================================================================
どうやらいくつか設定が必要なようだ。
3. 手動でdevise用の設定を行う。
- development.rbに追加。
config/environmets/development.rbに以下の文を追加。
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
- routes.rbに追加。
deviseではログイン処理を行うと、rootに設定されたページにリダイレクトするようになっている。
config/routes.rbを編集する。なお、homeコントローラとindexアクションが定義されているものとする。
root :to => "home#index"
- application.html.erbに追加。
app/view/layouts/application.html.erbに以下の文を追加。
<%= notice %>
<%= alert %>
- 認証用のモデルを作成する。
% rails generate devise user
4. ログイン画面へのリンクを作成する。
app/view/home/index.html.erbに以下の文を追加。
<% if user_signed_in? %>
<%= link_to "ログアウト", destroy_user_session_path, method: :delete %>
<% else %>
<%= link_to "ログイン", new_user_session_path %>
<% end %>
これでログイン画面へのリンクが貼られる。
☆私がはまったところ
先述のように、deviseではログイン処理を行うと、rootに設定されたページにリダイレクトするようになっている。しかし、私の場合はrootの設定を行っていてもそこにリダイレクトされず、localhost:3000にリダイレクトされていた。
調べてみたところ、ルーティングの設定を行っても静的なHTMLページの方が優先されて表示されてしまうとのこと。今回のケースでは「public/index.html」が存在しており、こちらが表示されていた。リネームしたらうまくいった。