June 20, 2008
In a certain application that I’m working on, accounts have subdomains. Nothing new. The column name I used for subdomain in the accounts table was…wait for it…subdomain! DHH’s account_location plugin, however, assumes username as the default attribute. Whatever was I to do? I liked subdomain but I didn’t want to have to pass it in each time I used the plugin methods.
Maybe this is a bad example as there are a crap load of really easy solutions to this problem (migration, change plugin, etc.) but I just used alias_attribute. The method was introduced way back in 1.2 and even made it into err’s rails advent calendar but I’ve never needed it until now.
class Account < ActiveRecord::Base alias_attribute :username, :subdomain end
Now, even though the column in the database is subdomain, the method username and username= work just like subdomain.
I can see this being more helpful when integrating with older systems. Stuff like aliasing less conventional attributes more like the conventions we now hold near and dear.