Rails meta_search gem:按关联模型的计数排序

jfe*_*ust 9 activerecord ruby-on-rails meta-search

我正在使用meta_search对表中的列进行排序.我的一个表列是特定模型的相关记录的计数.

基本上是这样的:

class Shop < ActiveRecord::Base
  has_many :inventory_records

  def current_inventory_count
    inventory_records.where(:current => true).count
  end
end

class InventoryRecord < ActiveRecord::Base
  belongs_to :shop

  #has a "current" boolean on this which I want to filter by as well
end
Run Code Online (Sandbox Code Playgroud)

在我的Shop #index视图中,我有一个表格列出了每个商店的current_inventory_count.无论如何使用meta_search按此计数订购商店?

我无法使用current_inventory_count方法,因为meta_search只能使用返回ActiveRecord :: Relation类型的自定义方法.

我能想到这样做的唯一方法是做一些自定义SQL,其中包括"虚拟"列中的计数,并按此列进行排序.我不确定这是否可能.

有任何想法吗?

我正在使用Rails 3.0.3和最新的meta_search.

Ana*_*use 8

要向结果集添加额外的列...

在Shop.rb ..

scope :add_count_col, joins(:inventory_records).where(:current=>true).select("shops.*, count(DISTINCT inventory_records.id) as numirecs").group('shops.id')

scope :sort_by_numirecs_asc, order("numirecs ASC")
scope :sort_by_numirecs_desc, order("numirecs DESC")
Run Code Online (Sandbox Code Playgroud)

在shops_controller.rb索引方法中

@search = Shop.add_count_col.search(params[:search])
#etc.
Run Code Online (Sandbox Code Playgroud)

在index.html.erb中

<%= sort_link @search, :numirecs, "Inventory Records" %>
Run Code Online (Sandbox Code Playgroud)

在这里找到sort_by__asc参考:http://metautonomo.us/2010/11/21/metasearch-metawhere-and-rails-3-0-3/