Railsで後からモデルにDeviseを追加

サインアップやログイン認証、忘れたパスワードの再発行なんかをMVCフルスタックでやってくれるというイケてそうなRailsプラグイン「Devise」を、すでにだいぶ作ったWebアプリで後からモデルに足そうと思ったら、どこにも既存モデルへの追加方法が書いてなくて困った。

色々探していたら、実際新規モデルを作る以外にDeviseを使ったモデルやらを生成する方法はなくて、Migrationファイルにたくさん並べてくれる以下のようなヘルパーがどんなカラムを生成するか、いったん適当なダミーモデルを作ってみて、生成されるスキーマからコピペするぐらいしか方法がないらしい。

% script/generate devise Account

で生成されるマイグレーションは、

create_table :accounts do |t|
    t.database_authenticatable
    t.confirmable
    t.recoverable
    t.rememberable
    t.trackable
    t.timestamps
end

実際に生成されるのは、以下のようなテーブル。

create_table "accounts", :force => true do |t|
  t.string   "email",                               :default => "", :null => f
alse
  t.string   "encrypted_password",   :limit => 128, :default => "", :null => f
alse
  t.string   "password_salt",                       :default => "", :null => f
alse
  t.string   "confirmation_token"
  t.datetime "confirmed_at"
  t.datetime "confirmation_sent_at"
  t.string   "reset_password_token"
  t.string   "remember_token"
  t.datetime "remember_created_at"
  t.integer  "sign_in_count",                       :default => 0
  t.datetime "current_sign_in_at"
  t.datetime "last_sign_in_at"
  t.string   "current_sign_in_ip"    t.string   "last_sign_in_ip"
  t.datetime "created_at"
  t.datetime "updated_at"
end

add_index "accounts", ["confirmation_token"], :name => "index_accounts_on_conf
irmation_token", :unique => true
add_index "accounts", ["email"], :name => "index_accounts_on_email", :unique =
> true
add_index "accounts", ["reset_password_token"], :name => "index_accounts_on_re
set_password_token", :unique => true

Railsは色々ジェネレータでコードを生成してくれてすごいなあと思うけど、始発で乗り損なったり、乗る電車や順番を間違えると結構戻るのが大変というか、結局てくてく隣駅まで歩くという、そんな感じが意外に多いような気がする。

名前の衝突がない限り、Deviseが必要とするフィールドをテーブルに足してくれるようなジェネレータがあればいいってことで、どうもそれは求められている機能らしい。