user346443
user346443

Reputation: 4862

Rails polymorphic association that multiple models access the same thing

How do you set up a polymorphic association where two different models have access to the same item

class Image < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
end

class ModelA < ActiveRecord::Base
   has_many :images, :as => :imageable
end

class ModelB < ActiveRecord::Base
   has_many :images, :as => :imageable
end

I would like ModelA and ModelB to access the same Image. So if ModelA updates an image ModelB image will be updated also.

UPDATE

I am attempting to create something like the following

enter image description here

Event has many images
Person has many images
Person and Event reference the same image
When a image is added to a person from an Event the record has extra attributes.

Can this be done though a polymorphic association?

Thank you

Upvotes: 0

Views: 139

Answers (1)

Santhosh
Santhosh

Reputation: 29174

I think you should use the relation between ModelA and ModelB to do this. Because images are not shared within ModelA. eg:

ModelA.find(1).images

is different from

ModelA.find(2).images

EDIT If i understand correctly, you dont need a polymorphic relation here.

You can just create this relation

In Person Model

has_many :event_images, :through => :person_event_images

Upvotes: 1

Related Questions