💎

Railsで動的にモデル作りたいよね。というお話。

2025/02/06に公開

Ruby on Railsで動的にモデル作りたいなーって話があったので備忘録としてまとめておきます。
初学者が故もっといいやつがあるかもしれない。

結論

これで作れます。

Object.const_set("Model名", Class.new(ApplicationRecord))

使い道

一時テーブル作るときに便利かなーとか思ってます。

model_name = "TemporaryTest"
Object.const_set(model_name, Class.new(ApplicationRecord))
ActiveRecord::Schema.define do
  create_table model_name.tableize.to_sym, force: true, temporary: true do |t|
    t.column :name, :string
  end
end
Object.const_get(model_name).create(name: :hoge)

こんなかんじ?

Discussion