Ruby on rails Rails元搜索gem:按关联模型的计数排序

Ruby on rails Rails元搜索gem:按关联模型的计数排序,ruby-on-rails,activerecord,meta-search,Ruby On Rails,Activerecord,Meta Search,我正在使用meta_搜索对表中的列进行排序。我的表列之一是特定模型的关联记录计数 基本上是这样的: class Shop < ActiveRecord::Base has_many :inventory_records def current_inventory_count inventory_records.where(:current => true).count end end class InventoryRecord < ActiveRecor

我正在使用meta_搜索对表中的列进行排序。我的表列之一是特定模型的关联记录计数

基本上是这样的:

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
class-Shoptrue)。计数
结束
结束
类InventoryRecord
在我的店铺索引视图中,我有一个表,列出了每个店铺的当前库存数量。是否有必要使用meta_搜索按此计数订购店铺

我不能使用当前的\u inventory\u count方法,因为元搜索只能使用返回ActiveRecord::Relation类型的自定义方法

我能想到的唯一方法是执行一些自定义SQL,它将计数包含在一个“虚拟”列中,并按此列进行排序。我不确定这是否可能

有什么想法吗


我使用的是Rails 3.0.3和最新的meta_搜索。

Rails有一个内置的解决方案,称为计数器缓存

在shops表上创建一个名为“inventory\u records\u count”的表列

class Shop < ActiveRecord::Base
  has_many :inventory_records, :counter_cache => true
end
class-Shop有\u多个:库存\u记录,:计数器\u缓存=>true
结束

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

在商店里

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")
车间内\u controller.rb索引方法

@search = Shop.add_count_col.search(params[:search])
#etc.
在index.html.erb中

<%= sort_link @search, :numirecs, "Inventory Records" %>


在这里找到按asc排序的参考:

我最好的办法是在商店中添加一个“当前库存记录计数”db列,我只需确保在保存前使用该列是正确的?谢谢,很高兴知道,但我只想计算标记为“当前”的库存记录。有多少:库存记录,:条件=>{:current=>true},:counter_cache=>true