我正在使用 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。
要将额外的列添加到结果集中...
在 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/ http://metautonomo.us/2010/11/21/metasearch-metawhere-and-rails-3-0-3/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)