ユーザ情報のメンテナンス
次にユーザ登録情報の修正を行なえるようにします。LoginEngineには、登録ユーザが自分の情報を対話的に修正する機能があるので、これを使用します。
まず、environment.rbの設定情報で、修正可能な項目にメールアドレスを追加します。
module LoginEngine # ...(省略) config :changeable_fields, [ 'firstname', 'lastname', 'email' ] end
それから、test_loginのコントローラとビューを以下のように変更しました。
class TestLoginController < ApplicationController before_filter :login_required, :only=>[:secret] def index store_location end def secret render_text 'secret' end end
<h1>TestLogin#index</h1> <% if user? %> <p>Hello, <%= current_user.login %></p> <% else %> <p>Hello, guest </p> <% end %> <ul> <% unless user? %> <li><%= link_to 'login', :controller => 'user', :action => 'login' %> <% end %> <li><%= link_to "to secret page", :action=>'secret' %> <% if user? %> <li><%= link_to 'edit user information', :controller => 'user', :action => 'edit' %> <% end %> <li><%= link_to 'logout', :controller => 'user', :action => 'logout' %> </ul>
この結果、以下のようになりました。
- indexメソッド内でstore_locationを呼ぶことにより、ログイン後にこのページに戻るようになった
- ゲスト(ログイン前)にはloginページへのリンクを表示
- ログイン後はindexページに戻る
- secretをクリックした場合はログインページを自動表示して、ログイン後、そのままsecretページを表示する
- ログイン済のユーザにはユーザ情報変更へのリンクを表示
なお、ログイン状態かどうかの判断は、current_userメソッドではなく、user?メソッドを使用した方がいいみたいです。