Chartkick:Rails Ruby 中的 Arel::Visitors::UnsupportedVisitError

Chartkick: Arel::Visitors::UnsupportedVisitError in Ruby on Rails

我正在使用 Chartkick gem 为 Rails 应用程序上的 Ruby 设计仪表板图。

我尝试使用 多系列 图表函数为付款数据显示 true 和 false 图表,这是一个布尔值 ( true 和 false)通过使用下面的代码。

<%= line_chart Donation.group(:payment).group_by_day(:created_at).count, colors: ["#342F49", "#FB4D00" ] %>

虽然显示了付款图表,但未显示 false 的标签,仅显示 true[=38 的标签=].我已附上问题的屏幕截图。

所以我决定根据 chartkick gem 文档向 multiple series 图表函数添加一个 name 选项为了使用下面的代码显示 true 和 false 的标签

<%= line_chart Donation.group(payment: [{name: "Series A", data: true}, {name: "Series B", data: false} ]).group_by_day(:created_at).count, colors: ["#342F49", "#FB4D00" ] %>

但是这次我得到了错误

Arel::Visitors::UnsupportedVisitError in Dashboard#index

Unsupported argument type: Hash. Construct an Arel node instead.

我曾尝试研究如何为此构建Arel节点,但尚未成功。我需要一些帮助。提前谢谢你。

我从 Reddit rails 社区 的一位成员那里得到了一些帮助,然后想出了如何让它发挥作用。

错误是由传递给 Donation.group 的散列值引起的。这是一个 ActiveRecord 方法,不是 Chartkick 提供的方法,因此它不理解传递给它的 name/data 哈希值。

需要颠倒操作顺序,以便chartkick config传递给line_chart函数,SQL查询参数传递给ActiveRecord .还强烈建议避免在视图层中进行数据库查询,因为这使得它们几乎无法测试。

所以这是我修复它的方法;

首先,在应用程序的 Helpers 文件夹中创建一个 charts_helper.rb 文件

app/helpers/charts_helper.rb

module ChartsHelper
  def donation_payments_chart_data
    [
      { name: 'true', data: Donation.group(:payment).group_by_day(:created_at).count, color: "#342F49" },
      { name: 'false', data: Donation.group(:payment).group_by_day(:created_at).count, color: "#FB4D00" }
    ]
  end
end

其次,在您的视图文件中,调用 app/helpers/charts_helper.rb

中定义的 donation_payments_chart_data 方法

app/views/dashboard/index.html.erb

<%= line_chart donation_payments_chart_data %>

就这些了。

希望对您有所帮助