Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic Association with multiple associations on the same model

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.

like image 691
Jamie Rumbelow Avatar asked Jul 22 '09 20:07

Jamie Rumbelow


People also ask

Is polymorphism a type of association?

Polymorphic association is a term used in discussions of Object-Relational Mapping with respect to the problem of representing in the relational database domain, a relationship from one class to multiple classes.

What is polymorphic association in Sequelize?

A polymorphic association consists on two (or more) associations happening with the same foreign key. For example, consider the models Image , Video and Comment . The first two represent something that a user might post. We want to allow comments to be placed in both of them.

How is polymorphic association set up in Rails?

The basic structure of a polymorphic association (PA)sets up 2 columns in the comment table. (This is different from a typical one-to-many association, where we'd only need one column that references the id's of the model it belongs to). For a PA, the first column we need to create is for the selected model.

What is polymorphic association Ruby?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. For example, we can use a single association to connect the Review model with the Event and Restaurant models, allowing us to connect a review with either an event or a restaurant.


2 Answers

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.

like image 147
Robert Avatar answered Oct 12 '22 23:10

Robert


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
like image 41
mylescarrick Avatar answered Oct 13 '22 01:10

mylescarrick