Note that there are some explanatory texts on larger screens.

plurals
  1. POSetting up a polymorphic has_many :through relationship
    primarykey
    data
    text
    <pre><code>rails g model Article name:string rails g model Category name:string rails g model Tag name:string taggable_id:integer taggable_type:string category_id:integer </code></pre> <p>I have created my models as shown in the preceding code. Articles will be one of many models which can have tags. The category model will contain all categories which may be assigned. The tag model will be a polymorphic join-table which represents tagged relationships.</p> <pre><code>class Article &lt; ActiveRecord::Base has_many :tags, :as =&gt; :taggable has_many :categories, :through =&gt; :taggable end class Category &lt; ActiveRecord::Base has_many :tags, :as =&gt; :taggable has_many :articles, :through =&gt; :taggable end class Tag &lt; ActiveRecord::Base belongs_to :taggable, :polymorphic =&gt; true belongs_to :category end </code></pre> <p>I can't seem to get this to work, I can do it non polymorphic, but I must have something wrong with the polymorphic part. Any ideas?</p> <p>Edit: Still not getting this right:</p> <pre><code>class Article &lt; ActiveRecord::Base has_many :taggables, :as =&gt; :tag has_many :categories, :through =&gt; :taggables, :source =&gt; :tag, :source_type =&gt; "Article" end class Category &lt; ActiveRecord::Base has_many :taggables, :as =&gt; :tag has_many :articles, :through =&gt; :taggables, :source =&gt; :tag, :source_type =&gt; "Article" end class Tag &lt; ActiveRecord::Base belongs_to :taggable, :polymorphic =&gt; true belongs_to :category end </code></pre>
    singulars
    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.
 

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