Rails meta_search gem: sort by count of an associated model

房东的猫 提交于 2019-12-04 03:48:46

To add extra columns to a result set...

In 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

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

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

Rails has a built-in solution for this called counter_cache

Create a table column named "inventory_records_count" on your shops table.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!