【问题标题】:Rails + ChartKick Pie Chart CountingRails + ChartKick 饼图计数
【发布时间】:2015-10-11 15:55:21
【问题描述】:

我有一个 Rails 应用程序,其中包含两个模型以及它们之间的关系。我正在使用 ChartKick 按邮政编码显示提供者订单的数量。

order.rb 模型

class Order < ActiveRecord::Base
belongs_to :user
belongs_to :provider
belongs_to :address

provider.rb 模型

class Provider < ActiveRecord::Base
  belongs_to :user
  has_many :orders

def past_orders_chart
    Order.where(:provider_id => self.id).where(:status => "2")
end

address.rb 模型

class Address < ActiveRecord::Base
   belongs_to :user
   has_many :orders 

past_orders.html.erb

<%= pie_chart @past_orders_chart.includes(:address).group(:zipcode).sum(:zipcode) %>

Here is how the chart looks using 'sum':

问题是根据上述命令对邮政编码求和是有意义的。

如果我将命令更改为“count”而不是“sum”,它会显示图表,但只计算邮政编码的唯一出现次数。

 pie_chart  =@past_orders_chart.includes(:address).group(:zipcode).count(:zipcode)

Here is how the chart looks using 'count':

使用“总和”可以直观地生成正确的饼图(以图表中显示的百分比表示。

所以问题是如何让图表列出邮政编码出现在数据集中的总次数? 我试图发布第三个示例屏幕截图,但被 SO 阻止。

谢谢,

大卫

【问题讨论】:

    标签: ruby-on-rails charts chartkick


    【解决方案1】:

    我将它移到模型中并能够通过以下方式解决它:

    def past_orders_chart
    
        Order.where(:provider_id => self.id).where(:status => "2").joins(:address).group(:zipcode).count
    
    end
    

    然后从控制器调用该方法作为@past_orders_chart 并将其传递给视图:

     <%= pie_chart @past_orders_chart, :library => {is3D: true } %>
    

    【讨论】:

      【解决方案2】:

      要调试该问题,您应该在 rails console 中运行和/或使用 .to_sql 查看正在运行的查询。

      这不是您标记的图表/chartkick 问题。

      使用 count 将以下内容添加到您的 SELECT 子句中:

      SELECT COUNT(DISTINCT zipcode) AS count_zipcode_id
      

      因此,如果您不计算邮政编码的不同值,则应将其替换为

      @past_orders_chart.includes(:address).group(:zipcode).select('COUNT(*) AS count_zipcode_id')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多