Shawn Deprey
Shawn Deprey

Reputation: 525

Rails3 - How do I get all attributes and associations of an ActiveRecord Model?

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.

Upvotes: 5

Views: 4206

Answers (2)

Siva
Siva

Reputation: 8058

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

Upvotes: 6

Shawn Deprey
Shawn Deprey

Reputation: 525

My solution is:

m = Model.find(id)
m.attributes.keys.concat(m.reflections.map{|r| r.first.to_s})

Upvotes: 3

Related Questions