68
44

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.

文字列からRailsのクラスにアクセスしたいとき

Posted at
"ModelName".constantize # -> ModelName

Rails3から導入された constantizeメソッドは、文字列が現在のネームスペース内で定数として存在していないか探し、存在していたらそれを返します。

クラスは定数なので、もしActiveRecordを継承して定義されたクラスの場合、そのままDBのレコードにアクセスすることもできます。

"ActiveRecordModelName".constantize.first # -> DB recordが返ってきます

使いどき

  • あるRailsプロジェクト外のDBから、データをマイグレートしているときに、マイグレート元とマイグレート後で、スキーマを結構変えました。

  • そこで、DatabaseConvertMapperというクラスを自作して、そこでDBのマイグレーションの対応表を作っていました。

  • その文字列からレコードにアクセスするときに使ってみました。他にも良い方法あればぜひ教えてください。

68
44
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
68
44

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?