Rails 5.1,用多种货币计算总和 [英] Rails 5.1, chartkick a sum with multiple currencies
问题描述
我遇到了一个关于 chartkick 的小问题.我有一个铁路应用程序,您可以在其中创建不同的货币.然后,您可以创建带有标题、金额的费用,并从列表和 user_id 中选择货币.关系已经建立并正在发挥作用.我的用户控制器中有这样的东西:
I'm stuck on a tiny problem regarding chartkick. I have a rail app where you can create different currencies. You can then create a expense with a title, a amount and choose the currency from a list and the user_id. The relations are made and working. I have in my user controller something like this :
@user_spendings = @current_user.spendings.all.order('date DESC').paginate(:page => params[:page], :per_page => 15)
@sums_by_currency = Currency.joins(:spendings).
select(:symb, 'SUM(spendings.amount) AS amount').
where(spendings: { id: @user_spendings.map(&:id) }).
group(:symb)
在我的显示视图中(因为我希望在此处显示每个用户的费用)是这样的:
And in my show view (as I want the expense from each user to be shown there) something like this :
<% @sums_by_currency.each do |currency| %>
<%= '%.02f' % "#{currency.amount}" %> <%= "#{currency.symb}" %>
<% end %>
这显示了每次支出的总和,具体取决于货币.
我想使用此总数并使用 chartkick 显示支出,以及创建此支出的日期.
我已经尝试了几件事
首先我只是为了看看:
That shows me the sum for each spending depending on the currency.
I would like to use this total and use chartkick to display the spending, with the date when this spending has been created.
I've tried several things already
First I went with this just to see :
<% @sums_by_currency.each do |currency| %>
<%= bar_chart currency.amount %>
<% end %>
好吧,我必须显示图表,但什么也没显示.也许循环不是解决方案.然后我想到了 .map,但我真的不知道如何将其落实到位.
我也试过这个:
Well I have to charts appearing but nothing shows up. Maybe the loop isn't the solution. Then I thought about the .map but I don't really know how to put that in place to be honnest.
I tried this aswell :
<%= line_chart @current_user.spendings.group(:date).sum(:amount) %>
这显示了所有货币的总支出.我必须找出如何在不同的图表中拆分所有货币并仅显示每种货币的总金额.
That shows me the total spendings from all the currencies. I have to find out how to split all the currencies in different charts and show only the total amount from each currency.
如果有人能给我一个线索,我将不胜感激.
If anyone can give me a clue I would appreciate it.
非常感谢.
推荐答案
好的,我明白了!
只花了我 2 天...
对于对答案感兴趣的人,我就是这样做的.我实际上并没有更改控制器中的任何内容,而是让 @sums_by_currency
保持原样.
相反,我去了:
Ok guys I got it !
Took me 2 days only...
For the one interested in the answer here is what I did. I actually didn't change anything in the controller and I let the @sums_by_currency
like it is.
Instead I went for that :
<%= column_chart @current_user.spendings.all.joins(:currency).group('currencies.symb').group_by_month(:date, format: "%B %Y").sum(:amount) %>
给我所有来自 current_user 的支出,我从那里加入了我按 symb 分组的货币.然后我按月对所有内容进行分组,然后从金额中得出总和.
Give me all the spendings from the current_user from where I joined the currency that I grouped by symb. Then I grouped everything by month and I get the sum from the amount.
这篇关于Rails 5.1,用多种货币计算总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!