Note that there are some explanatory texts on larger screens.

plurals
  1. PORails Polymorphic Association with multiple associations on the same model
    text
    copied!<p>My question is essentially the same as this one: <a href="https://stackoverflow.com/questions/1168047/polymorphic-association-with-multiple-associations-on-the-same-model">Polymorphic Association with multiple associations on the same model</a></p> <p>However, the proposed/accepted solution does not work, as illustrated by a commenter later.</p> <p>I have a Photo class that is used all over my app. A post can have a single photo. However, I want to re-use the polymorphic relationship to add a secondary photo.</p> <p>Before:</p> <pre><code>class Photo belongs_to :attachable, :polymorphic =&gt; true end class Post has_one :photo, :as =&gt; :attachable, :dependent =&gt; :destroy end </code></pre> <p>Desired:</p> <pre><code>class Photo belongs_to :attachable, :polymorphic =&gt; true end class Post has_one :photo, :as =&gt; :attachable, :dependent =&gt; :destroy has_one :secondary_photo, :as =&gt; :attachable, :dependent =&gt; :destroy end </code></pre> <p>However, this fails as it cannot find the class "SecondaryPhoto". Based on what I could tell from that other thread, I'd want to do:</p> <pre><code> has_one :secondary_photo, :as =&gt; :attachable, :class_name =&gt; "Photo", :dependent =&gt; :destroy </code></pre> <p>Except calling Post#secondary_photo simply returns the same photo that is attached via the Photo association, e.g. Post#photo === Post#secondary_photo. Looking at the SQL, it does WHERE type = "Photo" instead of, say, "SecondaryPhoto" as I'd like...</p> <p>Thoughts? Thanks!</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