Incorporating runtime parameters in a has_many :conditions c

Hi,
I was wondering if there was any way to include runtime parameters in
the :conditions clause of a has_many relationship?

I’m trying to model the concept of a person who goes by various
nicknames. My Person model contains a “name” attribute containing their
real name, and a “has_many :nicknames” relationship. Through my
business rules, I’m enforcing the requirement that a person’s real name
is always included in the database as a nickname.

(If this seems like a really bad data structure, I’m open to
suggestions. However, having weighed up various alternatives, this
seems to me to be the least worst solution.)

I now want to add an “alternative_nicknames” relationship, which will
comprise all of the person’s nicknames excluding their real name.
I’ve tried

has_many :alternative_nicknames, :class_name => “Nickname”,
:conditions => [“nickname <> ?”, self.name]

  • however, since has_many is a class-level method, the :conditions
    block is evaluated at the point of loading the class, and therefore
    self.name returns “Person” rather than the person’s name. Out of
    desperation I’ve even tried wrapping the has_many declaration in an
    after_initialize callback, but then it complains that has_many is not
    defined. The examples in the Rails docs and the Pragmatic book only
    demonstrate static SQL fragments being used in the :conditions clause,
    not ones incorporating parameters. Any ideas how I can achieve this?

(If it helps explain things any better, I believe this person’s
(unanswered) question is equivalent to mine:
http://groups.google.com/group/rubyonrails-talk/msg/5006b300e4e5a8cc )

  • Matt