26 Aug 2011

Default Attributes on Active Record Associations in Rails

I implemented a quick hack today to extend an Active Record association such that you can define default attributes:

What we’re doing is extending the association proxy object with a module that overrides the build and create methods such that they use the default values returned by the default_attributes method. Much neater than setting them elsewhere, no?

I love this sort of meta-programming in Ruby, it’s so much nice than the way we used to do it in the bad old days using alias_method_chain.