根据 HABTM 或 HMT 相关记录的数量进行搜索排序
Ransack sort on count of HABTM or HMT associated records
我在 Theme
和 Quote
模型之间有 HABTM 关系。 themes
index
视图显示与每个主题关联的引用数。我想在该列上添加一个 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。
任何帮助将不胜感激。
有一些补丁可以帮助您使用范围
访问 https://gist.github.com/ledermann/4135215
假设您使用上述范围查询了您的实体,例如您的索引查询始终具有:
# 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
中的排序名称?
我在 Theme
和 Quote
模型之间有 HABTM 关系。 themes
index
视图显示与每个主题关联的引用数。我想在该列上添加一个 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。
任何帮助将不胜感激。
有一些补丁可以帮助您使用范围 访问 https://gist.github.com/ledermann/4135215
假设您使用上述范围查询了您的实体,例如您的索引查询始终具有:
# 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
中的排序名称?