rails3でdeviseを使う
以前、「rails3+DataMapperでdeviseを使う」について書きましたが、datamapperを使わない時の方法ものせておきます。(ほとんど同じですが。。。)
アプリケーションの作成
devise用アプリケーションを作成します。
$ rails new devise-app $ cd devise-app
Gemfileを編集
$ vi Gemfile --------------- gem 'devise' <- 追加 ---------------
devise用ライブラリのインストール
$ bundle install $ rails g devise:install
deviseのセットアップ
public/index.htmlファイルの削除
$ rm public/index.html
routes.rbの編集
$ vi config/routes.rb ---------------- root :to => "welcome#index" ----------------
welcomeコントローラーの作成
$ rails g controller welcome index
deviesが使用する標準ビューを作成
$ rails g devise:views
userモデルの作成
$ rails g devise user
今回はユーザー登録をしたらメールを送信するようにします。
userモデルの編集
$ vi app/models/user.rb ---------------- :confirmableを追加します devise :database_authenticatable, :registerable, :confirmable, :recoverable, :rememberable, :trackable, :validatable ----------------
migrateファイルの修正
$ vi db/migrate/20110416111502_devise_create_users.rb ---------------- コメントアウトされている項目を有効にします。 ~ t.encryptable t.confirmable ~ add_index :users, :confirmation_token, :unique => true ----------------
サンプルファイルの作成
$ rails g scaffold hoge title:string body:text
マイグレーションの実行
$ rake db:create $ rake db:migrate
routes.rbの編集
$ vi config/routes.rb ---------------- root :to => "welcome#index" devise_for :users get 'hoges', :to => 'hoges#index', :as => :user_root resources :hoges ----------------
welcome#indexの編集
以下を追記
$ vi app/view/welcome/index.html.erb --------------- <%= content_tag(:p) do %> <%= link_to "ログイン", [:new, :user_session] %> <% end -%> <%= content_tag(:p) do %> <%= link_to "ユーザー登録", [:new, :user_registration] %> <% end -%> <%= content_tag(:p) do %> <%= link_to "パスワード再発行", [:new, :user_password] %> <% end -%> ---------------
welcomeコントローラーの修正
class WelcomeController < ApplicationController def index if current_user redirect_to :user_root return end end end
hogesコントローラーの修正
class HogesController < ApplicationController before_filter :authenticate_user! <- 追加 (省略) end
application.html.erbの編集
$ vi app/view/layout/application.html.erb --------------- <%= link_to('Sign out', [:destroy, current_user, :session],:class => 'signOut') if current_user%> <%= content_tag(:p, notice, :class => 'notice') %> <- 追加 <%= content_tag(:p, alert, :class => 'alert') %> <- 追加 <%= yield %> ---------------
development 環境でユーザーをするとターミナルにメールの内容が表示されます。
メールの中に確認用URLがあるので、コピーしてブラウザで開くとユーザー登録を確認したことになります。