5

I was looking for a method to get an array of all model attributes and associations on an ActiveRecord model. I had a hard time finding the answer to this question, so, I will post my answer and see if there is a better solution.

Shawn Deprey
  • 467
  • 8
  • 27

2 Answers2

5

To get all attributes

m = Model.new
m.attributes

To get all Model associations

Model.reflect_on_all_associations.map{|x| x.class_name}.compact

These links will provide more details How do you discover model attributes in Rails

http://www.funonrails.com/2009/11/how-to-get-all-associted-models-of.html

Community
  • 1
  • 1
Siva
  • 7,780
  • 6
  • 47
  • 54
  • Note that reflect_on_all_associations.map{|x| x.class_name} get the *class name* of the association, not the association name itself. – ericpeters0n Jan 16 '17 at 20:52
3

My solution is:

m = Model.find(id)
m.attributes.keys.concat(m.reflections.map{|r| r.first.to_s})
Shawn Deprey
  • 467
  • 8
  • 27