gpt4 book ai didi

ruby-on-rails - 根据 HABTM 或 HMT 相关记录的数量进行搜索排序

转载 作者:行者123 更新时间:2023-12-04 02:07:31 24 4
gpt4 key购买 nike

我在 ThemeQuote 模型之间有一个 HABTM 关系。 themes index View 显示与每个主题关联的引用计数。我想在该列上添加一个 Ransack sort_link,这样 themes 就可以按照相关 quotes 的计数进行排序。

我已经通过使用计数器缓存列的 has_many 关联成功完成了此操作,但 Rails 不支持 HABTM 关联的计数器缓存列。

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

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”,但到目前为止我所有的尝试都失败了。

我正在使用 Rails 4.2.2、ARel 6.0.4 和 PostgreSQL 9.5.4。

任何帮助将不胜感激。

最佳答案

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

# 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 中的排序名称?

关于ruby-on-rails - 根据 HABTM 或 HMT 相关记录的数量进行搜索排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41984939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com