For example: I have a Company with many legal_representatives and a
LegaRepresentative that has many companies.
In this case you use a has_and_belongs_to_many or has_many :through?
What's reasoning that leads me to select has_and_belongs_to_many
rather than has_many :through?
You choose has_many :through when you need to "decorate" the junction between the two models. Let's say that you needed to capture the date that a particular legal representative entered into an agreement with a company. You can't capture that in the strict habtm relationship -- that's just a "dumb" join table and can only store the fact that the relationship exists.
The usual reason for using has_many :through (hmt) is that you need to
attach some information to that relationship. For instance, you may
want to record exactly *when* a given Legal_representative started
representing a given Company, how much they're charging, etc. If you
are absolutely sure you don't, and *never will*, need to attach any
info to the relationship, then has_and_belongs_to_many (habtm) will do
fine.
BUT:
First, but I've heard some people complain about difficulty getting
that working (I haven't, and don't know what they were doing wrong),
and secondly, if you're wrong, I've heard that it's very difficult to
retrofit an existing habtm setup to become hmt (haven't tried to do
that myself).
So, aside from declaring one more class, there's no reason not to use
hmt from the start.
Ok, that's good, if I need or not to attach information to the
relationship I can always use has_many :through.
Can you suggest a name for the :through model between Company and
LegalRepresentative?
Off the top of my head, maybe LegalRepresentation? Or since it's so
close to an existing class, maybe just Representation? (Unless the
Company needs other forms of Representation.)
The usual reason for using has_many :through (hmt) is that you need to
attach some information to that relationship. For instance, you may
want to record exactly *when* a given Legal_representative started
representing a given Company, how much they're charging, etc. If you
are absolutely sure you don't, and *never will*, need to attach any
info to the relationship, then has_and_belongs_to_many (habtm) will do
fine.
BUT:
First, but I've heard some people complain about difficulty getting
that working (I haven't, and don't know what they were doing wrong),
and secondly, if you're wrong, I've heard that it's very difficult to
retrofit an existing habtm setup to become hmt (haven't tried to do
that myself).
So, aside from declaring one more class, there's no reason not to use
hmt from the start.
I've also tried hmt and I find it too much complicated in practice. My use
case is not exactly the same and starts from the simplest relationship.
Say you have customers doing orders for meals we'll have to bill for. We start
from models like this: