Rails将图像与产品相关联的方式?

ama*_*acy 0 ruby-on-rails associations

我有两个型号,ProductImage.Product有两列:namedescription.Image还有两列:( path即foobar.jpg)和description(用于标题和alt信息).大多数图像描绘了多个产品,每个产品都有多个图像.每个产品都有自己的页面,其中包含所有相关图像的图库.

最初我认为解决这个问题的最佳方法是HABTM协会 - 但我已经读过(在The Rails 3 Way中)那些现在不赞成这种has_many :through联想.但在这里创建第三个模型似乎很愚蠢.

我考虑过的另一个解决方案是,在每个产品页面上搜索Image descriptionProduct :name.但这似乎不是一个优雅的解决方案.

什么是Rails解决这个问题的方法?

小智 5

使用has_many :through将是rails方式,但底层数据结构仍然可以是相同的.我会用这种方式模拟关系:

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
Run Code Online (Sandbox Code Playgroud)

换句话说,HABTM之间的唯一区别has_many :through是关系声明和额外模型.是的,额外的模型可能看起来有点过分,但它并没有减损代码的可维护性.