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.