skalogirou
skalogirou

Reputation: 147

has_one through has many

Hello can please anyone help me with the associations? I have an article with ONE preview image and MANY article images.Images can be used to many articles. So my models are:

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

The problem is that with this code I get the error :

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

If I create into articles a new association for the preview_image like this :

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

doesn't seem to work correctly. Can someone please suggest me a solution

Thanks in advance

Upvotes: 0

Views: 2159

Answers (2)

Rodrigo_at_Ximera
Rodrigo_at_Ximera

Reputation: 548

Your "ArticleImage" doesn't seem right. It belongs both to a "preview image" and to a "main image", when it should have a single image there (of any type). The only way that model would make sense, is adding some constraint that one and only one of those two properties has a value and the other is null.

Also, do you have more properties in ArticleImage? Why make a :through association for the preview image? Why not make:

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

And have in this class the foreign key of the one and only preview image?

Upvotes: 0

Chowlett
Chowlett

Reputation: 46677

I would make preview a column on the article_images table. Then do:

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

class ArticleImage
  belongs_to :Article
end

Upvotes: 3

Related Questions