我正在使用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 View 中,我有一个表,列出了每个Shop的current_inventory_count。无论如何,是否可以使用meta_search通过此计数来订购商店?
我不能使用current_inventory_count方法,因为meta_search只能使用返回ActiveRecord::Relation类型的自定义方法。
我能想到的唯一方法是执行一些自定义SQL,该SQL将“虚拟”列中的计数包括在内,并按此列进行排序。我不确定这是否有可能。
有任何想法吗?
我正在使用Rails 3.0.3和最新的meta_search。
最佳答案
要向结果集中添加额外的列...
在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")
在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/