Basic ActiveRecord questions


I'm a 2 day old Ruby on Rails programmer (and a 2 day Ruby programmer!) and have a question about defining Models and their cardinality. I've bought "Ruby on Rails: Up and Running" which is a good source of information but it's not very comprehensive so I hope you can help me figure this out. I'm hoping by the time I've finished this e-mail I'll have got things straight in my mind and figured it out for myself...

I have two table definitions: company and natural_person ("natural_person" is a legal word referring to a real blood-and-bones person as opposed to a "legal person" which includes companies). "Company" has a "contact" field which is a reference to "natural_person". This is a many-to-one relationship as a person can be a contact for a number of companies but a company has only one contact. So far so good.

I need to associate other "natural person"s with the company as {owner, shareholder, partner, director, secretary, etc}. (I've defined a static table "relationship" that defines those relationships.) The link between company and natural_person in this case is many-to-many: a company can have many "whatevers", and a natural person can fulfill one or more of those roles with one or more companies. As per the example on page 44 of "Up and Running" I need to use a relationship table in order to implement this relationship.

Here's my quandary: The two separate links between the tables are causing a conflict in my ActiveRecord classes (actually the conflict may just be in my brain). According to my interpretation of the ActiveRecord documentation I need to define "has_many/belongs_to" *and* "has_and_belongs_to_many" for the company and natural_person classes. Is that right? Maybe it is...

One solution is to delete the "contact" reference from "company" and add "contact" as another relationship in my relationships table. Doing this would lose the many-to-one cardinality and I would have to add extra checking to make sure there is only one contact per company. I'm not going to go down this track because, to be honest, what I'm doing is pretty basic stuff and I'm sure ActiveRecord will be able to handle it, I just haven't got my head around it yet.

OK, I'll stop now lest I confuse myself further. If you can make sense of my ramblings please take pity and shed some light on this for me!