What will let me know if I am going to get a Relation, Array, or some other type back from an ActiveRecord call? I know I can type .class in the console and figure it out, but is there something in the call itself that will let me know what I am asking for?
Share
You know, Rails sometimes lies to you — all magicians do 🙂
Rails allows you to build complex queries by chaining your
has_manyassociations. The core of this functionality is a bunch of XXXAssocation (likeHasManyAssociation) classes.When you call
.classon ahas_manyassociation your call is applied in fact forHasManyAssociationinstance. But here’s the magic starts:Rails undefs (hides) methods of
HasManyAssociationinstance (except the few, as you can see in the regular expression) and then uses delegation andmethod_missingto pass your call to some underlying array (if you’re trying to fetch records) or to association itself (if you’re chaining your association):So,
HasManyAssociationinstance decides what to handle by itself and what needs to be accomplished via hidden array (classmethod isn’t whatHasManyAssociationinterested in so it will be called on this hidden array. The result, of course, will beArray, which is a little deception).