ActiveRecord経由でテーブルのフィールド型を得る方法
ActiveRecord::Baseクラスのcolumnsメソッドでカラムの情報が取得できます。
nameにフィールド名、typeにフィールド型が入っています。
null | NULL値の許可 |
sql_type | SQL型 |
name | フィールド名 |
scale | 位取り |
precision | 精度 |
limit | ? |
type | フィールド型 |
default | デフォルト値 |
primary | プライマリキー |
CREATE文でusersテーブルを作ってActiveRecordからカラム情報を参照してみます。
テーブル定義
CREATE TABLE users ( id serial, name text, age int, email text, tel text, created_at timestamp, updated_at timestamp );
ActiveRecordでカラム情報を参照する
require 'rubygems' require 'active_record' # ------------------------------------------------------------ # 接続情報 # ------------------------------------------------------------ ActiveRecord::Base.establish_connection( :adapter => "postgresql", :host => "192.168.xxx.xxx", :username => "myusername", :password => "mypassword", :database => "mydatabase", :encoding => "utf8" ) # ------------------------------------------------------------ # ActiveRecord::Baseクラス # ------------------------------------------------------------ class User < ActiveRecord::Base end # ------------------------------------------------------------ # カラム情報を得る # ------------------------------------------------------------ puts sprintf("|%20s|%20s|%30s|", "column_name", "column_type", "column_sql_type") puts sprintf("+--------------------+--------------------+------------------------------+") User.columns.each { |column| puts sprintf("|%20s|%20s|%30s|", column.name, column.type, column.sql_type) }
出力結果
| column_name| column_type| column_sql_type| +--------------------+--------------------+------------------------------+ | id| integer| integer| | name| text| text| | age| integer| integer| | email| text| text| | tel| text| text| | created_at| datetime| timestamp without time zone| | updated_at| datetime| timestamp without time zone|