ActiveRecord::Base#attribute_names
で取得できるけど、has_many
などで定義された属性名は取得できない。アソシエーションで定義された属性は
ActiveRecord::Base#reflections
経由で取得できる。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
user = User.first | |
# association で定義された属性の名前を取得 | |
user.reflections.keys | |
# belongs_to で定義された属性の名前を取得 | |
user.reflections.select { |_, ref| ref.macro == :belongs_to }.keys | |
# through 経由で定義された属性の名前を取得 | |
user.reflections.select { |_, ref| ref.is_a?(ActiveRecord::Reflection::ThroughReflection) }.keys |
ActiveRecord::Base#attribute_names
は文字列の配列を返すけど、こっちはシンボルの配列を返す。