Controller method to do fuzzy search for companies
Unless I've misjudged what you're going for, this should work (it's not pretty though, I'm sure there's an even better way)

def search
  @query = params[:query].try(:strip) # strip here instead

  unless @query.blank?
    tags = Tag.where("name LIKE ?", "%#{@query}%").pluck(:name)
    @companies  = Company.tagged_with(tags, :any =&gt; true).includes(:vouchers) # eager load vouchers
    @vouchers   = [
      Voucher.tagged_with(tags, :any =&gt; true),
      companies.map(&amp;:vouchers)
    ].flatten.uniq
    @categories = @vouchers.map(&amp;:categories).uniq
  else
    # you need something here, by the way...
  end
end


If you don't need each of the collections in the search results, but only need the categories, you should probably add this to the Company model

has_many :categories, :through =&gt; :vouchers


then you can do

def search
  @query = params[:query].strip # strip here instead

  unless @query.blank?
    tags = Tag.where("name LIKE ?", "%#{@query}%").pluck(:name)
    vouchers  = Voucher.tagged_with(tags, :any =&gt; true).includes(:categories)
    companies = Company.tagged_with(tags, :any =&gt; true).includes(:categories)

    @categories = [vouchers, companies].flatten.map(&amp;:categories).flatten.uniq
  end
end


However, I'd think about restructuring the database if possible, to avoid the mix of 1st and 2nd order associations.