pariser
pariser

Reputation: 275

Rails determine if association is has_one or has_many

Wondering if there is an easy way to determine dynamically if a model's association is a "has_one" or "has_many" relationship (i.e. is this an association to one object or many).

I'm using MongoMapper, so I am able to check if a class klass has an associated model assoc with a one or many relationship via

klass.associations[:assoc].is_a? MongoMapper::Plugins::Associations::OneAssociation
klass.associations[:assoc].is_a? MongoMapper::Plugins::Associations::ManyAssociation

but this seems rather clunky, and isn't generic (i.e. won't work for ActiveRecord associations as well). I'd also like to avoid loading any objects, so I'm pretty sure that instance.assoc.is_a? Array is out too.

Any ideas?

Upvotes: 9

Views: 3845

Answers (1)

MCB
MCB

Reputation: 2073

UPDATE: So, I happened upon the Reflections Class methods http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html

You can get all the has_many, belongs_to, etc. with reflect_on_all_associations method. It's all in there. Or you can put in an association into reflect_on_association and it will tell you if it is a has_many, has_one, etc. Specifically:

Model.reflect_on_association(:assoc).macro

This should be sufficient for all cases. It doesn't actually solve the problem I'm currently working on, but it should solve this.

Upvotes: 12

Related Questions