开发者

Meta_Search: Search on number of associated entries

开发者 https://www.devze.com 2023-03-29 05:26 出处:网络
I have the following Rails models: class Entry < ActiveRecord::Base has_and_belongs_to_many :tags, :uniq => true

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消