amacy
amacy

Reputation: 280

the Rails Way of associating images with products?

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?

Upvotes: 0

Views: 795

Answers (1)

user1454117
user1454117

Reputation:

Using has_many :through would be the rails way, but the underlying data structure can still be the same. I would model the relationships this way:

class Product
  has_many :product_images
  has_many :images, :through => :product_images
end

class ProductImage
  belongs_to :product
  belongs_to :image
end

class Image
  has_many :product_images
  has_many :products, :through => :product_images
end

So in other words the only difference between HABTM and has_many :through is 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.

Upvotes: 5

Related Questions