Is there a way to find out what associations a model has? Take these 2 models:
class Comment < ActiveRecord::Base belongs_to :commentable end class Post < ActiveRecord::Base has_many :comments belongs_to :user end
I'm looking for something like:
Post.has_many #=> ['comments', ...] Post.belongs_to # => ['user'] Comment.belongs_to # => ['commentable']
Association in Rails defines the relationship between models. It is also the connection between two Active Record models. To figure out the relationship between models, we have to determine the types of relationship. Whether it; belongs_to, has_many, has_one, has_one:through, has_and_belongs_to_many.
They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user .
You're looking for reflect_on_all_associations
.
So in short:
Post.reflect_on_all_associations(:has_many)
...will give an array (of object with attributes like name
, etc) of all has_many
associations.
The following will list all the associations for a particular instance of Post.
#app/models/post.rb def list_associations associations = [] User.reflect_on_all_associations.map(&:name).each do |assoc| association = send assoc associations << association if association.present? end associations end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With