Skip to content

Instantly share code, notes, and snippets.

@rhannequin
Created July 28, 2016 16:19
Show Gist options
  • Save rhannequin/3a077a7f85110f3ec37ee46155960edf to your computer and use it in GitHub Desktop.
Save rhannequin/3a077a7f85110f3ec37ee46155960edf to your computer and use it in GitHub Desktop.
Issue while trying to exclude articles with specific tag using Rails 5 and polymorphic association

ActiveRecord excluding polymorphic association issue

Considering this situation with Rails 5: I have an Article model and a Tag model. An article has many tags, and a tag can belong to many articles. My schema then looks like this:

class Article < ApplicationRecord
  has_many :taggings, as: :taggable
  has_many :tags, through: :taggings
end

class Tagging < ApplicationRecord
  belongs_to :taggable, polymorphic: true
  belongs_to :tag
end

class Tag < ApplicationRecord
  has_many :taggings, dependent: :destroy
  has_many :articles, through: :taggings, source: :taggable, source_type: 'Article'
end

My goal is to find every article which has not a specific tag (with name "ignore").

ignored_tag_id = Tag.select(:id).find_by(name: 'ignore').id
articles_with_this_tag = Article.joins(:taggings).where.not(taggings: { tag_id: ignore_tag.id })

This successfully excludes every article which includes the tag "ignore", unless this article has another tag. If my article has two tags, including the "ignore" one, it is selected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment