简体   繁体   English

Rails meta_search gem:按关联模型的计数排序

[英]Rails meta_search gem: sort by count of an associated model

I'm using meta_search to sort columns in a table. 我正在使用meta_search对表中的列进行排序。 One of my table columns is a count of the associated records for a particular model. 我的一个表列是特定模型的相关记录的计数。

Basically it's this: 基本上是这样的:

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

In my Shop#index view I have a table that lists out the current_inventory_count for each Shop. 在我的Shop #index视图中,我有一个表格列出了每个商店的current_inventory_count。 Is there anyway to use meta_search to order the shops by this count? 无论如何使用meta_search按此计数订购商店?

I can't use my current_inventory_count method as meta_search can only use custom methods that return an ActiveRecord::Relation type. 我无法使用current_inventory_count方法,因为meta_search只能使用返回ActiveRecord :: Relation类型的自定义方法。

The only way I can think about doing this is to do some custom SQL which includes the count in a "virtual" column and do the sorting by this column. 我能想到这样做的唯一方法是做一些自定义SQL,其中包括“虚拟”列中的计数,并按此列进行排序。 I'm not sure if that's even possible. 我不确定这是否可能。

Any Ideas? 有任何想法吗?

I'm using Rails 3.0.3 and the latest meta_search. 我正在使用Rails 3.0.3和最新的meta_search。

To add extra columns to a result set... 要向结果集添加额外的列...

In Shop.rb .. 在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")

In shops_controller.rb index method 在shops_controller.rb索引方法中

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

In index.html.erb 在index.html.erb中

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

Found the sort_by__asc reference here: http://metautonomo.us/2010/11/21/metasearch-metawhere-and-rails-3-0-3/ 在这里找到sort_by__asc参考: http ://metautonomo.us/2010/11/21/metasearch-metawhere-and-rails-3-0-3/

Rails has a built-in solution for this called counter_cache Rails有一个内置的解决方案,称为counter_cache

Create a table column named "inventory_records_count" on your shops table. 在商店表上创建名为“inventory_records_count”的表列。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM