Search code examples
ruby-on-railsruby-on-rails-4tagsacts-as-taggable-on

Rails acts as taggable on, get all related objects that have a certain tag


I have a n-to-n relation between Foo and Bar and Bar is a taggable object.

class Foo < ActiveRecord::Base
  has_many :xx
  has_many :bars, through: :xx
end

class Bar < ActiveRecord::Base
  has_many :xx
  has_many :foos, through: :xx
  acts_as_taggable
end

I'm using the acts as taggable on gem; I'd like to know if there is there a way to use tagged_with to get all Foo objects that have a Bar object tagged with a certain tag?

Example:

Foo.with_bar_tagged_with("input_search_tag")
#=> #<ActiveRecord::Relation [#<Foo>,...]

Solution

  • Finally solved using the following:

    Foo.joins(:bars).where("bars.id IN ?",Bar.tagged_with("input_search_tag")).uniq