Interface or Not: Creating Polymorphic Model Relationships in Ruby on Rails Dynamically
Please bear with me for a moment as I try to explain exactly what I would like to achieve.
In my Ruby on Rails application, I have a model called Page.
It is a web page.
I would like to enable user to arbitrarily attach components to the page. Some examples of "components" are Picture, PictureCollection, Video, VideoCollection, Background, Audio, Form, Comments.
I currently have a direct link between page and image:
class Page < ActiveRecord::Base
has_many :pictures, :as => :imageable, :dependent => :destroy
end
class Picture < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end
This relationship allows the user to associate an arbitrary number of images with the page. Now, if I want to provide multiple collections, I need an additional model:
class PictureCollection < ActiveRecord::Base
belongs_to :collectionable, :polymorphic => true
has_many :pictures, :as => :imageable, :dependent => :destroy
end
And change the page to link to the new model:
class Page < ActiveRecord::Base
has_many :picture_collections, :as => :collectionable, :dependent => :destroy
end
The user can now add any number of image collections to the page.
However, this is still very static with respect to the link: picture_collections in the page model. If I add another "component" like: video_collections, I need to declare another link on the page for that type of component.
So my question is:
Do I need to add a new link for each component type or is there some other way? In ActionScript / Java, I declare an interface Component and force all components to implement that interface, then I can only have one attribute: components that contain all dynamically linked model objects.
This is Rails, and I'm sure there is a great way to achieve this, but its complicated Google approach. Perhaps you good people have some wise suggestions. Thanks in advance for taking the time to read and answer this.
a source to share
I believe you can only use
class Page < ActiveRecord::Base
has_many :components, :as => :attachable, :dependent => :destroy
end
class Picture < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true
end
class PictureCollection < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true
has_many :pictures, :as => :imageable, :dependent => :destroy
end
etc.
a source to share