9

テーブル内の列をソートするために meta_search を使用しています。テーブルの列の 1 つは、特定のモデルに関連付けられたレコードの数です。

基本的にはこれです:

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 を使用する方法はありますか?

meta_search は ActiveRecord::Relation タイプを返すカスタム メソッドしか使用できないため、current_inventory_count メソッドを使用できません。

これを行うことについて考えることができる唯一の方法は、「仮想」列にカウントを含むカスタム SQL を実行し、この列で並べ替えを行うことです。それが可能かどうかはわかりません。

何か案は?

Rails 3.0.3 と最新の meta_search を使用しています。

4

2 に答える 2

8

結果セットに列を追加するには...

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")

shop_controller.rb の index メソッドで

@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/

于 2011-04-23T01:41:06.430 に答える
4

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

于 2011-03-16T13:23:47.353 に答える