ActiveRecord Default Association Extensions

Let’s say we want a helper method #build_fuzzy everywhere we have a collection of socks.

At first we might think to put it in an a collection extension module:

Now we have to remember to add it to every Sock association:

And we also need to include it in Sock:

…but this doesn’t work:

And anyway, we want this to be available globally without explicitly extending associations.

Next, we try adding a class method to the Sock class. Since ActiveRecord association proxies delegate missing methods to the assoication class, it seems like this should work.

This is a complete failure. While the association does forward the .build_fuzzy call to Sock, once in the call it is operating in the context of the class object, which as we saw before has no #build method.

However, a slight change makes everything work as hoped:

Now when we call #build_fuzzy on the class it builds a fuzzy sock unassociated with any drawer, and when we call it on an association it builds a fuzzy sock with the appropriate drawer ID set:

All this thanks to the #scoped method, which is aware of the current scope.

Thank you to Dan Kubb for figuring this out for me.

UPDATE: Fixed def build_fuzzy to be def self.build_fuzzy in the last two examples.