I have a Cubicle model that will have many Printers, Phones,
whatever. In the past, HABTM has sufficied, but each of the joins
will need the capability to store additional attributes inside of the
respective table. From what I’ve read, this is only a feature of
using a join model – has_many :through it is.
I want to be able to do @cubicle.printers, @cubicle.phones, etc. as
well as @phone.cubicle, @printer.cubicle, so the relationship needs to
be bidirectional.
What I have is functioning, but given that this is my first time using
has_many :through, I’d like to run my solution by the group to see if
- I am setting up the relationships correctly and 2) if there is a
better (cleaner?) way.
For each join case, I create a model and a table. So for the cubicles
<–> printers relationship, I have a model cubilces_printer.rb, a
table called cubicles_printers that has the necessary foreign keys and
additional attributes, and establish the relationships as so:
CubiclePrinter
belongs_to :cubicle
belongs_to :printer
Printer
has_many :cubicles_printers
has_many :cubicles :through => :cubicles_printers
Cubicle
has_many :cubicles_printers
has_many :printers :through => :cubicles_printers
I think this is right, it just feels odd initially building the middle
layer model. My brain wants to just say Cubicle has_many :printers
given that the Printer model is already defined and have Rails just
know, sort of like HABTM, to look for the join in the
cubicles_printers table. But I guess the difference comes in with the
additional model attributes.