Polymorphic association with multiple associations on the same model

I am a little confused about the polymorphic association that I have. I need an article model to have a header image and many images, but I want to have one image model. To make things even more confusing, the image model is polymorphic (so that other resources can have many images).

I use this association in my article model:

class Article < ActiveRecord::Base has_one :header_image, :as => :imageable has_many :images, :as => :imageable end 

Is it possible? Thank.

+7
ruby ruby-on-rails activerecord polymorphic-associations
Jul 22 '09 at 20:29
source share
2 answers

Yeah. It is possible.

You may need to specify a class name for header_image because it cannot be defined. Include :dependent => :destroy to ensure that images are destroyed if the article is deleted.

 class Article < ActiveRecord::Base has_one :header_image, :as => :imageable, :class_name => 'Image', :dependent => :destroy has_many :images, :as => :imageable, :dependent => :destroy end 

then on the other end ...

 class Image < ActiveRecord::Base belongs_to :imageable, :polymorphic => true end 
+4
Jul 23 '09 at 0:17
source share

I tried this, but then header_image returns one of the images. Just because there is no other type of image use specified in the image table (header_image vs. normal image). He simply says: imageable_type = Image for both uses. Therefore, if there is no information about the type of use, ActiveRecord cannot distinguish.

+6
Nov 19 '09 at 15:31
source share



All Articles