LoginSignup
0
0

More than 5 years have passed since last update.

Rails: 指定したカラムを持つ全てのmodel名を取得する

Last updated at Posted at 2017-05-02
def models_with_attribute(attr)
  ActiveRecord::Base.connection.tables.
    select{ |table| table.classify.safe_constantize&.has_attribute?(attr) }
end

 => ["ModelA",
 "ModelB",
 "ModelC"]
  • @QUANONさんから教えてもらったselectを加えて更にシンプルになりました。
0
0
3

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
0
0