LoginSignup
1
0

More than 3 years have passed since last update.

既存DBから ActiveRecord::Attributesのattribute を雑に生成するスクリプト

Posted at

Rails 5 から導入された ActiveRecord::Attributes では、レコードのカラムをRuby側のコードに明示して、デフォルト値や型変換などに役立てることができます。

class User < ApplicationRecord
  attribute :id, :integer
  attribute :name, :string
  attribute :email, :string
end

ですが、Rails 5 以前からアップデートしてきた場合には、当然、attribute は定義されていません。では、DB定義とにらめっこしながら、手打ちするしかないのでしょうか?

雑に生成するスクリプト

.connection のメソッドを使えば、テーブル名やカラム定義にアクセスできます。なので、こんなスクリプトを書けば良いでしょう。

# columns.rb
# bin/rails r columns.rb のように実行する

# コネクションを取得
conn = ApplicationRecord.connection

# 抽出したいテーブル名を書く
tables = %w[
  users
  products
]

# カラムの情報を出力する
tables.each do |t|
  puts t
  conn.columns(t).each do |c|
    puts "  attribute :#{c.name}, :#{c.sql_type_metadata.type}"
  end
end
1
0
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
1
0