I’ve got two models, Product and Image. Product has two columns: name and description.Image also has two columns: path (i.e., foobar.jpg) and description (for captions and alt info). Most images depict multiple products and there are multiple images of each product. Each product has its own page that will feature a gallery of all relevant images.
Originally I thought the best way to solve this would be a HABTM association – but I’ve since read (in The Rails 3 Way) that those are now frowned upon in favor of the has_many :through association. But creating a third model seems silly here.
Another solution I’ve considered is to, on each product page, search the Image description column for the Product :name. But this doesn’t seem like an elegant solution.
What’s the Rails Way to solve this problem?
Using
has_many :throughwould be the rails way, but the underlying data structure can still be the same. I would model the relationships this way:So in other words the only difference between HABTM and
has_many :throughis the relationship declarations and the extra model. Yes, the extra model may seem like overkill, but it doesn’t detract from the maintainability of the code.