You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 7分组数据排序及Chartkick轴排序问题问询

解决方案

1. 修复查询排序问题

你之前的order("count(...) DESC")写法不规范,需要明确指定统计字段,推荐用Arel写法避免SQL注入风险:

@completed_tasks = Task.where(completed: true).group(:user_id).order(Arel.sql('count(user_id) DESC'))

也可以用原生SQL写法(确保字段名正确):

@completed_tasks = Task.where(completed: true).group(:user_id).order("count(user_id) DESC")

2. 禁用Chartkick轴自动排序

Chartkick默认会对X轴标签排序,要保留查询返回的原始顺序,只需在bar_chart方法中添加sort: false参数。

3. 重命名Y轴标签

通过y_label参数可以自定义Y轴的显示名称。

最终视图代码示例

<%= bar_chart @completed_tasks.count, sort: false, y_label: "已完成任务数量" %>

低版本Ruby兼容提示

如果你的Ruby版本低于2.0,Hash是无序结构,建议把统计结果转为有序数组:

# 控制器中
@completed_tasks_data = Task.where(completed: true).group(:user_id).order(Arel.sql('count(user_id) DESC')).count.to_a

视图中使用该数组:

<%= bar_chart @completed_tasks_data, sort: false, y_label: "已完成任务数量" %>

内容的提问来源于stack exchange,提问作者Liuba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 06:25:22