Railsで会員制サービスを構築するときに便利なメモ

Railsを使って簡単な会員制サービスを構築するメモ。
このパターン通りにいけば5分で会員制サービスのプロトタイプができるはず。
Rails 2.0.2で動作確認。
時間があったらrestful_authenticationを試したいと思う。

プロジェクト作成

rails testapp -d mysql
cd testapp
rake db:create

acts_as_authenticatedインストール

script/plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_authenticated
script/generate authenticated user account
rake db:migrate

acts_as_authenticated設定

app/controllers/application.rbのClass定義内に以下の記述を追加

  # Be sure to include AuthenticationSystem in Application Controller instead
  include AuthenticatedSystem
  # If you want "remember me" functionality, add this before_filter to Application Controller
  before_filter :login_from_cookie

map.rootをaccountコントローラに接続
config/routes.rbの下記の行を修正

# map.root :controller => "welcome"
↓
map.root :controller => "account"

public/index.htmlを削除

app/views/account/index.rhtmlを下記の内容に変更

<%= link_to '会員登録', :action => "signup" %>
<% if logged_in? %>
	現在<%= h current_user.login %>としてログイン中
	<%= link_to 'ログアウト', :action => "logout" %>
<% else %>
	ログインしていません。
	<%= link_to 'ログイン', :action => "login" %>
<% end %>

サーバー起動/確認

script/server

その他

これをベースに、必要に応じてログイン認証をログインIDではなくメールアドレスで行うように変更したり、アカウント登録時にメールでアクティベーションを行うように変更したりして使っている。
プロトタイプ、ということを考えればメールの認証は面倒だしこれで十分だと思う。