9

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.

sth
  • 222,467
  • 53
  • 283
  • 367
Jamie Rumbelow
  • 4,967
  • 2
  • 30
  • 42
  • 6
    has_one is synctactic sugar for has_many :limit => 1 – François Beausoleil Jul 23 '09 at 23:09
  • possible duplicate of [Rails Polymorphic Association with multiple associations on the same model](http://stackoverflow.com/questions/2494452/rails-polymorphic-association-with-multiple-associations-on-the-same-model) – Joshua Pinter May 28 '15 at 17:38

2 Answers2

7

I tried this, but then header_image returns one of the images. Simply because the images table doesn't specify a different image use type (header_image vs. normal image). It simply says: imageable_type = Image for both uses. So if there's no information stored about the use type, ActiveRecord cannot differentiate.

Robert
  • 1,936
  • 27
  • 38
4

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
mylescarrick
  • 1,680
  • 8
  • 10
  • 1
    I'm five years late to the party, but for future reference see [this question and answer](http://stackoverflow.com/questions/2494452/rails-polymorphic-association-with-multiple-associations-on-the-same-model). – Brian Mar 14 '14 at 16:57
  • 1
    Pease cancel this as the accepted answer. This solution does not work, see comment above by @Sooie. The real solution is in: http://stackoverflow.com/questions/2494452/rails-polymorphic-association-with-multiple-associations-on-the-same-model – tommyalvarez Aug 18 '16 at 21:35