Ransack 排序 HABTM 或 HMT 相关记录的计数 [英] Ransack sort on count of HABTM or HMT associated records

查看:35
本文介绍了Ransack 排序 HABTM 或 HMT 相关记录的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ThemeQuote 模型之间建立了 HABTM 关系.themes index 视图显示与每个主题关联的引用计数.我想在该列上添加一个 Ransack sort_link,以便 themes 可以按照它们关联的 quotes 的计数进行排序.

I have a HABTM relationship between the Theme and Quote models. The themes index view displays the count of quotes associated with each theme. I'd like to add a Ransack sort_link on that column, so the themes can be sorted by their count of associated quotes.

我使用计数器缓存列成功地使用 has_many 关联完成了此操作,但 Rails 不支持 HABTM 关联的计数器缓存列.

I have done this successfully with has_many associations using a counter cache column, but Rails does not support counter cache columns for HABTM associations.

到目前为止,我已经有了一个作用域,它向 Theme 模型添加了一个名为 quotes_count 的虚拟属性(通过执行单个查询,避免 N+1):

So far, I've got a scope that adds a virtual attribute called quotes_count (by performing a single query, avoiding N+1) to the Theme model:

scope :with_quotes_count, -> do
  joins('LEFT OUTER JOIN quotes_themes on quotes_themes.theme_id = themes.id')
    .select('themes.*, COUNT(quotes_themes.quote_id) as quotes_count')
    .group('themes.id')
end

似乎我必须使用 ARel 将上述范围转换为Ransacker",但到目前为止我的所有尝试都失败了.

Seems like I have to convert the above scope into a "Ransacker" using ARel but so far all my attempts have failed.

我使用的是 Rails 4.2.2、ARel 6.0.4 和 PostgreSQL 9.5.4.

I'm using Rails 4.2.2, ARel 6.0.4 and PostgreSQL 9.5.4.

任何帮助将不胜感激.

推荐答案

假设您使用上述范围查询实体,例如您的索引查询始终具有:

Given you have your entities queried with the above scope, for example your index query always has:

# controller
@search = Theme.ransack(params[:q])
@themes = @search.result(distinct: true).with_quotes_count

试试:

# model
ransacker :quotes_count_sort do
    Arel.sql('quotes_count')
end

并使用sort_link中的排序名称?

这篇关于Ransack 排序 HABTM 或 HMT 相关记录的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆