22
16

More than 5 years have passed since last update.

ActiveRecordでカラムの情報を確認したい

Posted at

やりたいこと

「このテーブルってどんなカラムがあるんだっけ?」となった時、一覧で確認したい。
けど、どこで見ればいいかわからない。

結論

db/schema.rbにありました。

ActiveRecord::Schema.define(version: 20180122145123) do

  enable_extension "plpgsql"

  create_table "users", force: :cascade do |t|
    t.string "name"
    t.integer "age"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
end

今までコンソールで、モデル名.column_namesしてました。カラム名しか取得できないけど。

User.column_names
 => ["id", "name", "age", "created_at", "updated_at"]

rails newするだけで生成される大量のディレクトリ・ファイルに圧倒されていたんですが、早い段階で各ディレクトリの概要だけでも把握しておいた方がいいですね。。。
Ruby on Rails ガイドとかRuby on Rails 5アプリケーションプログラミング(P24)でなんとなく全体像が掴めます。

22
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
16