9

我正在使用 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

在我的 Shop#index 视图中,我有一个表格,列出了每个商店的 current_inventory_count。反正有没有使用 meta_search 按这个计数来订购商店?

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

我可以考虑这样做的唯一方法是执行一些自定义 SQL,其中包括“虚拟”列中的计数并按此列进行排序。我不确定这是否可能。

有任何想法吗?

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

4

2 回答 2

8

要将额外的列添加到结果集中...

在商店.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")

在shops_controller.rb 索引方法中

@search = Shop.add_count_col.search(params[:search])
#etc.

在 index.html.erb 中

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

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

于 2011-04-23T01:41:06.430 回答
4

Rails 有一个内置的解决方案,称为 counter_cache

在您的商店表上创建一个名为“inventory_records_count”的表列。

class Shop < ActiveRecord::Base
  has_many :inventory_records, :counter_cache => true
end

http://asciicasts.com/episodes/23-counter-cache-column

于 2011-03-16T13:23:47.353 回答