Rails meta_search gem:按关联模型的计数排序
我正在使用 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。
I'm using meta_search to sort columns in a table. 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. Is there anyway to use meta_search to order the shops by this count?
I can't use my current_inventory_count method as meta_search can only use custom methods that return an ActiveRecord::Relation type.
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. I'm not sure if that's even possible.
Any Ideas?
I'm using Rails 3.0.3 and the latest meta_search.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要向结果集中添加额外的列...
在 Shop.rb 中 ..
在shops_controller.rb 索引方法中
在index.html.erb 中
找到 sort_by__asc 参考: http://metautonomo.us/2010/11/21/metasearch-metawhere-and-rails-3-0-3/
To add extra columns to a result set...
In Shop.rb ..
In shops_controller.rb index method
In index.html.erb
Found the sort_by__asc reference here: http://metautonomo.us/2010/11/21/metasearch-metawhere-and-rails-3-0-3/
Rails 有一个内置的解决方案,称为 counter_cache
在您的商店表上创建一个名为“inventory_records_count”的表列。
http://asciicasts.com/episodes/23-counter-cache-column
Rails has a built-in solution for this called counter_cache
Create a table column named "inventory_records_count" on your shops table.
http://asciicasts.com/episodes/23-counter-cache-column