deviseでさくっと認証作る
有名なやつ。 結論、ちょう簡単にできる。
https://github.com/plataformatec/devise ドキュメントが親切。
Install
Gemfileに追記。
gem 'devise'
bundle install rails g devise:install
初期設定
devise:installしたら設定項目が表示されるので迷うことはないのだが。
- config/environments/development.rb
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config/environments/production.rb developmentと同じ物を、本番のドメインで。
config/routes.rb
root :to => "top#index"
これは認証後の画面なので好きなとこで。 - app/views/layouts/application.html.erb
<p class="notice"><%= notice %></p> <p class="alert"><%= alert %></p>
モデルを作る
rails g devise User
モデルは好きなかんじで。まあだいたいUserだろうけど。
これでもう、localhost:3000いくとできてる!!!! アホか!!!!
メール確認する場合
Confirmableというオプションを使う。 - migration file(たぶんdb/migrate/20121215012513_devise_create_users.rbみたいなの) カラムとINDEXを追加(コメントアウトするだけ)
## Confirmable t.string :confirmation_token t.datetime :confirmed_at t.datetime :confirmation_sent_at t.string :unconfirmed_email # Only if using reconfirmable ... add_index :users, :confirmation_token, :unique => true
- Userモデル deviseメソッドに:confirmable を追加(コメント書いてあるし迷わないとおもわれる)
あとメールの設定必要。
Viewのカスタム
rails g devise:views
ってやると、各種画面のViewが生成されるので、好きにいじることができる。
devise:viewsのhaml化
でも生成されるのはerb...しかも昔はhamlで生成ができたらしいが今はできない。。 そこでhtml2hamlを使う。 https://github.com/plataformatec/devise/wiki/How-To:-Create-Haml-and-Slim-Views
基本的には、
gem install haml hpricot ruby_parser slim haml2slim for i in `find app/views/devise -name '*.erb'` ; do html2haml -e $i ${i%erb}haml ; rm $i ; done
でいけるのだが、html2hamlがhaml', '>= 3.2.0.beta.1'なので注意。