简体   繁体   中英

Meta_Search: Search on number of associated entries

I have the following Rails models:

class Entry < ActiveRecord::Base
  has_and_belongs_to_many :tags, :uniq => true
end

And

class Tag < ActiveRecord::Base
  has_and_belongs_to_many :entries, :uniq => true
end

Just so it's clear, an 'entry' can have many 'tags' associated with it.

Using the plugin Meta_Search I would like to be able to perform a search (via a form) that returns 'entries' that have more than 0 tags associated with it.

I've tried several techniques including (named) scopes and methods but I've not been able to achieve this.

Does anyone have an idea on how to perform this?

Thanks.

Something like

Entry.joins(
        :tags
      ).select(
        "entries.*, count(tags.id) as tags_count"
      ).order(
        "tags_count DESC"
      ).group( 
        "entries.id"
      ).where(
        "tags_count != 0"
      )

This is similar to sorting by a count of associated records: Rails meta_search gem: sort by count of an associated model One of those answers recommends using counter_cache, but a comment suggests it won't work for HABTM.

Use a named scope that can select the records you are interested in (a la @mark's answer) and make it a search_method .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM