HomeRamblings  ⁄  ProgrammingCSS

CSS

Cascading Style Sheets

Rails has and belongs to many (habtm) demystified

Every time I have to implement a many-to-many relationship between Rails models, I seem to have to figure out how to do it effectively all over again. Especially as Rails seems to evolve the relational hooks with better support and elegance. Here, I will show a has_and_belongs_to_many strategy that works well for me. Along the way, I'll expose a few other minor tricks, such as adding a custom inflector for pluralizing your model or not adding the ID column on a table declaration. The following Browser Edit form is what we're going for. That is, having a list of Operating Systems to check off while editing a Browser object: ![Editing Browser View][1] First, the models: What I wanted, was a way to declare browsers (Firefox, Explorer, Opera, etc.) and associate them with one or more operating systems (OS X, Windows,… read more