Note that there are some explanatory texts on larger screens.

plurals
  1. PORails: delete polymorphic STI has_many through association fails
    text
    copied!<p>I have a model called User which has many "taxonomies" associated through a Classification model. One of these taxonomies is a model called Topic (inheriting from Taxonomy). My model User is also called a "classifiable".</p> <p><em>EDIT: Added more models to clarify the problem</em></p> <pre><code>class User &lt; ActiveRecord::Base has_many :classifications, :as =&gt; :classifiable, :foreign_key =&gt; :classifiable_id has_many :topics, :through =&gt; :classifications, :source =&gt; :taxonomy, :source_type =&gt; "Topic" end class Taxonomy &lt; ActiveRecord::Base end class Topic &lt; Taxonomy has_many :classifications, :as =&gt; :taxonomy, :foreign_key =&gt; :taxonomy_id, :source_type =&gt; "Topic" has_many :professionals, :through =&gt; :classifications, :source =&gt; :classifiable, :source_type =&gt; "User", :conditions =&gt; {:is_a_professional =&gt; true} has_many :questions, :through =&gt; :classifications, :source =&gt; :classifiable, :source_type =&gt; "Question" has_many :guides, :through =&gt; :classifications, :source =&gt; :classifiable, :source_type =&gt; "Guide" end class Classification &lt; ActiveRecord::Base attr_accessible :classifiable, :classifiable_id, :classifiable_type, :taxonomy, :taxonomy_id, :taxonomy_type belongs_to :classifiable, :polymorphic =&gt; true belongs_to :taxonomy, :polymorphic =&gt; true end </code></pre> <p>Everything works well except when I want to delete an association.</p> <pre><code>user = User.find(12) # any user topic = user.topics.last # any of his topics user.topics.delete(topic) </code></pre> <p>The SQL ActiveRecord runs is the following:</p> <pre><code>DELETE FROM "classifications" WHERE "classifications"."classifiable_id" = 12 AND "classifications"."classifiable_type" = 'User' AND "classifications"."taxonomy_id" = 34 AND "classifications"."taxonomy_type" = 'Taxonomy' </code></pre> <p>Clearly, the taxonomy_type is wrong, it should be 'Topic' and not 'Taxonomy'.</p> <p>Since I am using polymorphic associations and STI, I had to config ActiveRecord as such:</p> <pre><code>ActiveRecord::Base.store_base_sti_class = false </code></pre> <p>However, it does not seem to trigger on collection.delete. Is this a bug with rails?</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