1

我有以下 Rails 模型:

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

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

很明显,一个“条目”可以有许多与之关联的“标签”。

使用插件 Meta_Search 我希望能够执行搜索(通过表单),返回具有多个关联标签的“条目”。

我尝试了几种技术,包括(命名的)范围和方法,但我无法实现这一点。

有谁知道如何执行此操作?

谢谢。

4

2 回答 2

0

这类似于按关联记录的计数进行排序:Rails meta_search gem:按关联模型的计数排序 其中一个答案建议使用 counter_cache,但有评论表明它不适用于 HABTM。

使用可以选择您感兴趣的记录的命名范围(@mark 的答案)并将其设为search_method.

于 2012-03-15T15:04:11.510 回答
0

就像是

Entry.joins(
        :tags
      ).select(
        "entries.*, count(tags.id) as tags_count"
      ).order(
        "tags_count DESC"
      ).group( 
        "entries.id"
      ).where(
        "tags_count != 0"
      )
于 2011-08-17T14:23:57.633 回答