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 1) 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.
on 2009-03-22 19:09
on 2009-03-22 20:49
On Mar 22, 6:08 pm, ericindc <ericmilf...@gmail.com> wrote: > > 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. I often find that has many through feels awkward when you haven't quite pinned down what the join model is and have to name it something like CubiclesPrinters (the classic example is having a join model called Subscription between Person and Magazine rather than MagazinesPeople). It obviously doesn't change what actually happens but finding a good name makes the relationship feel more natural rather than a hoop you jump through to make active record happy Fred
on 2009-03-22 23:54
I think you're entirely right. But I struggle to find a meaningful, yet natural-feeling name. But besides the name, it still feels a tad awkward having the join model. It feels unnecessary, though the additional attributes require it. Thanks for the response. On Mar 22, 3:48 pm, Frederick Cheung <frederick.che...@gmail.com>