ユーザー登録ページとログインページを作る
まずは、ログイン用のコントローラを作る
ruby script\generate controller Login add_user delete_user list_users login logout
ユーザー登録ページを作るには、まず、view/login/add_user.rhtmlを編集し、ビューを構築する。
<% @page_title = "Add a User" -%>
<%= error_messages_for 'author' %>
<%= form_tag %>
<table>
<tr>
<td>User name</td>
<td><%= text_field("author", "name") %></td>
</tr>
<tr>
<td>Password</td>
<td><%= password_field("author", "password") %></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value=" ADD USER " /></td>
</tr>
</table>
<%= end_form_tag %>
次に先ほど自動生成されたLoginコントローラをいじってみる。
class LoginController < ApplicationController
def add_user
if request.get?
@author = Author.new
else
@author = Author.new(params[:author])
if @author.save
flash[:notice] = "Author #{@author.name} created"
redirect_to(:action => "index")
end
end
end
end
@author = Author.new(@params[:author])でpostされたデータを基にAuthorのインスタンスを生成し、@author.saveで保存(DB保存)する。
このときにパスワードをハッシュ値化する場合は、ActiveRecordのCallbackを使う。
Callbackのうち、before_createというメソッドが、createの直前に呼ばれる。
あとは、Digest::Baseでハッシュ化というわけ。
といことで、class Author < ActiveRecord::Baseに
def before_create
self.password = Digest::MD5.hexdigest(self.password)
end
を加えれば、ハッシュ値化されたパスワードが保存される。
次にログインでは、ログインコントローラに
def login
if request.get?
session[:user_id] = nil
@author = Author.new
else
@author = Author.new(params[:author])
logged_in_user = @author.try_to_login
if logged_in_user
#ログイン後画面へ
else
#エラー画面へ
end
end
end
Authorモデルクラスに
def try_to_login
self.password = Digest::MD5.hexdigest(self.password)
begin
Author.find(:first, :conditions => ["name = ? and password = ?", self.name, self.password])
rescue
return nil
end
end
を追加する。