Set default values for has_one association

Sometimes you simply want to set some default values for an associated model within ActiveRecord without thinking too much of creating possible side effects when overriding methods like build_association or add model callbacks. The following example demonstrates the easiest way so far to achieve the desired functionality.

For this we use the two models User and Subscription, whereas a user may have one single subscription of a specific kind. The kind of a subscription is defined by a enumeration (ActiveRecord::Enum) with predefined values for demonstration purpose only. To set a default value for the kind attribute of the association, we simply have to add a scope and the magic happens on its own. Each time the association gets called, the scope will be executed and this is true for all added class methods of the has_one association too. So when calling the build_subscription method of a user, a new Subscription instance will be built and the kind will be preset to :single.

To get a better understanding, you can find the complete example below.






Leave a Reply

Your email address will not be published. Required fields are marked *