Note that there are some explanatory texts on larger screens.

plurals
  1. POPossible Misuse of Polymorphic Association of Model in Rails 3
    primarykey
    data
    text
    <p>In my app I have three models of interest. The first is the Patient model, which has_many Record models. Similarly the Record model has_many Diagnosis models. Initially I had the Patient model accessing the diagnoses via:</p> <pre><code>:has_many :diagnoses, :through =&gt; :records </code></pre> <p>However the problem I had with this was that <strong>I also want the Patient model to be able to create a Diagnosis object independent of the Record model</strong>. For instance during an admission the patient might be diagnosed with a new condition. However she might also have a history of having a condition (a prior diagnosis) and so I would like to keep track of that without having to resort to creating a new model.</p> <p>I tried using polymorphic associations as described <a href="http://guides.rubyonrails.org/association_basics.html#polymorphic-associations" rel="nofollow">here</a>, such that my models look like:</p> <pre><code>class Patient &lt; ActiveRecord::Base has_many :records has_many :diagnoses, :as =&gt; :medical_history # ... end class Record &lt; ActiveRecord::Base belongs_to :patient has_many :diagnoses, :as =&gt; :medical_history # ... end class Diagnosis &lt; ActiveRecord::Base belongs_to :medical_history, :polymorphic =&gt; true # ... end </code></pre> <p>The problem I'm having is that while I can successfully create Diagnosis objects via the Record object, when I call <code>p.diagnoses</code> (where <code>p</code> is a Patient object) it doesn't give me access to all the Diagnosis objects like I expect it to.</p> <p><em>To reiterate, what I want is to be able to create a Diagnosis object either through the Record model or through the Patient model, but be able to have the Patient model access all Diagnosis objects that were either created through itself or via the Record model (which should be possible since the Record model belongs to the Patient model).</em></p> <p>I'm pretty sure this is me not really understanding how polymorphic associations work and I could be totally misusing polymorphic associations as well. So I appreciate all the help. Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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