This whole situation is a mess, but I’ll see if I can explain it well.
I have two models, User and Company. I’d like user to be able to get
company.name. I’m aware of the problems with using @user.company.name,
because of company is nil, then name throws an error.
So originally, I wrote this method instead
company ? company.name : nil
This works, however, rather than use that, I would like to use
The problem I ran into with that,
however, is that user also has a name. So I can’t simply write
delegate :name, :to => :company
because that will overwrite name. It would be nice if there was a
:company_name, :as => :name, :to => :company, but as far as I know this
doesn’t exist. So… I thought I would use “delegate :company_name: to
:company”, and alias :company_name to :name within company, like so:
alias :company_name :name
however, that will not work with Active Record models, because name is
defined until the class is instantiated. I could just write a wrapper
method, aka def class_name; name; end; but that adds an extra method
that I’d rather not have. So finally, I came up with this solution:
alias_method :company_name, :name
This works, because the first time company_name is called, it calls name
instantiate it (needed the first call for some reason), then it opens
class and aliases company_name to name. Lastly, it returns name, so
works as intended on the first call as well.
This code does work, I have tested it, but it seems like an awful lot of
work for what seems like a simple concept. Maybe I’m just making things
complicated, and should have simply used my company_name method within
I don’t know.
If anyone can suggest a better way to solve this problem, it would be