簡體   English   中英

Rails meta_search gem:按關聯模型的計數排序

[英]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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM