0

您好,请任何人帮助我与协会?我有一篇带有一个预览图像和许多文章图像的文章。图像可用于许多文章。所以我的模型是:

class Article 
  has_many :article_images
  has_many :main_images, :class_name => "Image", :through => :article_images
  has_one  :preview_image, :class_name => "Image", :through => :article_images
end

class ArticleImage
  belongs_to :article
  belongs_to :preview_image, :class_name => "Image", :foreign_key => :image_id, :conditions => ["images.itype = 'preview_image'"]
  belongs_to :main_image, :class_name => "Image", :foreign_key => :image_id, :conditions => ["images.itype = 'main_image'"]
end

class Image < ActiveRecord::Base
  has_many :article_images
  has_many :articles
end

问题是使用这段代码我得到了错误:

ActiveRecord::HasOneThroughCantAssociateThroughCollection: Cannot have a has_one :through association 'Article#preview_image' where the :through association 'Article#article_images' is a collection. Specify a has_one or belongs_to association in the :through option instead

如果我在文章中为 preview_image 创建一个新关联,如下所示:

has_one :article_image
has_one  :preview_image, :class_name => "Image", :through => :article_image

似乎无法正常工作。有人可以建议我一个解决方案吗

提前致谢

4

2 回答 2

3

我会preview在桌子上做一列article_images。然后做:

class Article 
  has_many :article_images
  has_one  :preview_image, :class_name => "ArticleImage", :conditions => {:preview => true}
end

class ArticleImage
  belongs_to :Article
end
于 2012-12-19T17:12:20.957 回答
0

您的“ArticleImage”似乎不正确。它既属于“预览图像”又属于“主图像”,当它应该有一个图像(任何类型)时。该模型有意义的唯一方法是添加一些约束,即这两个属性中的一个且只有一个具有值,而另一个为空。

另外,您在 ArticleImage 中有更多属性吗?为什么要为预览图像创建一个 :through 关联?为什么不做:

class Article 
  has_many :article_images
  has_many :main_images, :class_name => "Image", :through => :article_images
  belongs_to  :preview_image, :class_name => "Image"
end

并且在这个类中有唯一的预览图像的外键?

于 2012-12-19T17:27:58.603 回答