13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

テーブル情報からModelを動的生成する方法 (ActiveRecordの単体利用時)

Last updated at Posted at 2013-11-12
# [前提]
#   以下の様なデータを持つusersテーブルが作成されているとする。
#     | id | name   |
#     |  1 | taro   |
#     |  2 | hanako |

require 'active_record'

# ここは使用するDBにあわせる(この例ではSQLite3)
ActiveRecord::Base.establish_connection(
  "adapter"  => "sqlite3",
  "database" => "./hoge.sqlite3"
)

# 各テーブルのModelを動的に作成する
ActiveRecord::Base.connection.tables.each do |table_name|
  class_name = table_name.singularize.camelcase
  self.class.const_set class_name, Class.new(ActiveRecord::Base)
end

# 以降、いつもどおりにModelを扱える
User.all
# => [#<User id: 1, name: "taro">, #<User id: 2, name: "hanako">]
13
13
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
13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?