Forum: Ruby on Rails Aliasing Active Record Attributes (also delegation issues)

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Tyler P. (Guest)
on 2007-01-20 22:06
(Received via mailing list)
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  I'm aware of the problems with using,
because of company is nil, then name throws an error.

So originally, I wrote this method instead

class User
  def company_name
    company ? : 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

class User
  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:

class Company
  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:

class Company
  def company_name
    self.class.class_eval do
      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
that it
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

Tyler P.
on 2007-01-21 06:03
(Received via mailing list)
I'm not entirely sure, but i think only trows an
error if @object.content is nil AND you're in development mode (whiny
nils is enabled). Not sure though.
Chris W. (Guest)
on 2007-01-21 11:49
(Received via mailing list)
On 1/20/07, Tyler P. <removed_email_address@domain.invalid> wrote:

> class Company
>   alias :company_name :name
> end

class Company
  alias_attribute :company_name, :name

Chris W.
Tyler P. (Guest)
on 2007-01-21 16:46
(Received via mailing list)

Thanks!  Much much better.  I had the feeling that there had to be a
way, and there it is.


P.S.  I really like your blog.  Lots of good information on there.
This topic is locked and can not be replied to.