【问题标题】:Rails meta_search gem: sort by count of an associated modelRails meta_search gem:按关联模型的计数排序
【发布时间】:2011-05-31 16:54:10
【问题描述】:

我正在使用 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。

【问题讨论】:

  • 我最好的选择是向商店添加一个“current_inventory_records_count”数据库列,我只是确保使用 before_save's 总是正确的?

标签: ruby-on-rails activerecord meta-search


【解决方案1】:

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

【讨论】:

  • 谢谢,很高兴知道,但我只想统计标记为“当前”的库存记录。
  • has_many :inventory_records, :conditions => { :current => true }, :counter_cache => true
【解决方案2】:

向结果集中添加额外的列...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    相关资源
    最近更新 更多