[英]Rails meta_search gem: sort by count of an associated model
我正在使用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/
Rails有一个内置的解决方案,称为counter_cache
在商店表上创建名为“inventory_records_count”的表列。
class Shop < ActiveRecord::Base
has_many :inventory_records, :counter_cache => true
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.