Solidify wrote:
Hi everyone, I have a simple question:
an author has a place of birth and a place of death. Both places
should come from the same table (cities). This should be a
many_to_many relationship, because one author may be born in the same
city where the other author dies.
That’s not a good spot for a many-to-many relationship. Rather, it’s
better modeled as two one-to-many relationships, where an author belongs
to one city as birthplace and one city as “deathplace”. Since the place
of birth and the place of death are semantically different, they should
not be shoved into the same association.
A better candidate for a many-to-many relationship would be a list of
places where an author resided throughout his life. Since they’re
semantically the same, it makes sense to do many-to-many here.
Now in the authors-table, one city_id would not be enough, it has to
be two fields, one for birth, one for death. but then, the
@author.city would not work anymore. Could anyone give me a hint how
to solve this?
@author.city is semantically meaningless. It shouldn’t be defined
from what you’ve said. You probably want something like (untested):
class Author < AR::B
belongs_to :birth_city, :class_name => ‘City’
belongs_to :death_city, :class_name => ‘City’
end
class City < AR::B
has_many :authors_born, :class_name => ‘Author’, :foreign_key =>
:birth_city_id
has_many :authors_died, :class_name => ‘Author’, :foreign_key =>
:death_city_id
end
Then you can use @author.birth_city and @author.death_city.
Does that help?
Best,
Marnen Laibow-Koser
http://www.marnen.org
[email protected]