June 20, 2008
Older: A Class Instance Variable Update
Newer: Don't Forget To Reserve Subdomains For Yourself
Alias Attribute
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.
2 Comments
Jun 20, 2008
Cool, I wasn’t sure if this was deprecated because it isn’t in the current API docs, but if it still works that’s great.
Jun 20, 2008
@Hugh – No, it doesn’t seem to be. Works fine in 2.1 and it’s located in active_support/core_ext/module/aliasing.rb along side alias_method_chain.
Sorry, comments are closed for this article to ease the burden of pruning spam.