你好可以请任何人帮助我协会吗?我有一篇文章有一个预览图像和许多文章图像。图像可用于许多文章。所以我的模型是:
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
似乎无法正常工作。 有人可以建议我一个解决方案
提前致谢
答案 0 :(得分: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
答案 1 :(得分:0)
您的“ArticleImage”似乎不对。当它应该具有单个图像(任何类型)时,它既属于“预览图像”又属于“主图像”。模型唯一有意义的方法是添加一些约束,即这两个属性中只有一个具有值而另一个属性为null。
另外,你在ArticleImage中有更多属性吗?为什么要通过关联预览图像?为什么不:
class Article
has_many :article_images
has_many :main_images, :class_name => "Image", :through => :article_images
belongs_to :preview_image, :class_name => "Image"
end
在这个类中有一个唯一的预览图像的外键吗?