Polymorphic Association with multiple associations on the same model
activerecord, polymorphic-associations, ruby, ruby-on-rails
Solution
Yep. That's totally possible.
You might need to specify the class name for `header_image`, as it can't be inferred. Include `:dependent => :destroy` too, to ensure that the images are destroyed if the article is removed
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
Problem
I'm slightly confused about a polymorphic association I've got. I need an Article model to have a header image, and many images, but I want to have a single Image model. To make matters even more confusing, the Image model is polymorphic (to allow other resources to have many images). I'm using this association in my Article model: ``` class Article < ActiveRecord::Base has_one :header_image, :as => :imageable has_many :images, :as => :imageable end ``` Is this possible? Thanks.