gpt4 book ai didi

ruby-on-rails - 用于 Lazy HighCharts 的 Rails ActiveRecord group_by & sum db 结果

转载 作者:行者123 更新时间:2023-12-04 18:39:22 24 4
gpt4 key购买 nike

我是 RoR/Ruby 的新手,我正在使用 Lazy High Charts gem 根据一些数据库信息生成一些 purdy 图表。
我已经尝试了上一个问题中提供的答案,但我仍然对如何做到这一点感到有些困惑。
我需要将 amount_used 和 billed_amount 相加并按月/年分组(例如;2012 年 8 月)
最终结果将类似于具有两个系列“使用量”和“成本”的双轴图表。此信息特定于某个 account_id。

发票表

+---------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| account_id | int(11) | YES | | NULL | |
| invoice_date | varchar(255) | YES | | NULL | |
| amount_used | float | YES | | NULL | |
| billed_amount | float | YES | | NULL | |
| comments | text | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+---------------+--------------+------+-----+---------+----------------+
Controller 图表代码
@account = Account.find(params[:id])
@invoices = Invoice.where("account_id = #{@account.id}").order("invoice_date DESC")

@h = LazyHighCharts::HighChart.new('area') do |f|
f.options[:chart][:defaultSeriesType] = "area"
#Sample dates right now, should be the grouped_by :invoice_date
f.xAxis( :categories => ['May', 'Jun', 'Jul'] )
f.yAxis([
{
:title => { :text => "Amount Used" }
},
{
:title => { :text => "Cost" },
:opposite => true
}
])
#Sample data right now, should be the summed amounts of the :amount_used correpsonding for each above grouped invoice_date
f.series(:name => "Amount Used", :data => [100,300,500] )
#Sample data right now, should be the summed amounts of the :billed_amount correpsonding for each above grouped invoice date
f.series(:name => "Cost", :yAxis => 1, :data => [200,400,600] )
end

最佳答案

看起来你已经准备好了一切。以下是从数据库中提取数据的方法:

@aggregated_invoices = Invoice.
where(:account_id => params[:id]).
order("invoice_date DESC").
group("invoice_date").
select("DATE_FORMAT(invoice_date, '%Y-%m-01') AS invoice_date, sum(amount_used) AS amount_used, sum(billed_amount) AS billed_amount")

# Then use these instead of sample data:
@categories = @aggregated_invoices.map {|i| i.invoice_date.strftime("%b/%Y")}
@amount_used_data = @aggregated_invoices.map(&:amount_used)
@billed_amount_data = @aggregated_invoices.map(&:billed_amount)

关于ruby-on-rails - 用于 Lazy HighCharts 的 Rails ActiveRecord group_by & sum db 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12371279/

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