Note that there are some explanatory texts on larger screens.

plurals
  1. POTo Interface or Not?: Creating a polymorphic model relationship in Ruby on Rails dynamically
    text
    copied!<p>Please bear with me for a moment as I try to explain exactly what I would like to achieve.</p> <p>In my Ruby on Rails application I have a model called Page. </p> <p>It represents a web page.</p> <p>I would like to enable the user to arbitrarily attach components to the page. Some examples of "components" would be Picture, PictureCollection, Video, VideoCollection, Background, Audio, Form, Comments.</p> <p>Currently I have a direct relationship between Page and Picture like this:</p> <pre><code>class Page &lt; ActiveRecord::Base has_many :pictures, :as =&gt; :imageable, :dependent =&gt; :destroy end class Picture &lt; ActiveRecord::Base belongs_to :imageable, :polymorphic =&gt; true end </code></pre> <p>This relationship enables the user to associate an arbitrary number of Pictures to the page. Now if I want to provide multiple collections i would need an additional model:</p> <pre><code>class PictureCollection &lt; ActiveRecord::Base belongs_to :collectionable, :polymorphic =&gt; true has_many :pictures, :as =&gt; :imageable, :dependent =&gt; :destroy end </code></pre> <p>And alter Page to reference the new model:</p> <pre><code>class Page &lt; ActiveRecord::Base has_many :picture_collections, :as =&gt; :collectionable, :dependent =&gt; :destroy end </code></pre> <p>Now it would be possible for the user to add any number of image collections to the page.</p> <p>However this is still very static in term of the :picture_collections reference in the Page model. If I add another "component", for example :video_collections, I would need to declare another reference in page for that component type. </p> <p>So my question is this:</p> <p>Do I need to add a new reference for each component type, or is there some other way? In Actionscript/Java I would declare an interface Component and make all components implement that interface, then I could just have a single attribute :components which contains all of the dynamically associated model objects.</p> <p>This is Rails, and I'm sure there is a great way to achieve this, but its a tricky one to Google. Perhaps you good people have some wise suggestions. Thanks in advance for taking the time to read and answer this.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload