问题
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 %>
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 %>
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.
Thanks alot.
回答1:
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) %>
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.
回答2:
Yeah, you need to pass a set of data to the chart, not lots of individual pieces of data for individual charts (ie what you've got with the loop). Using map
to convert your currency-objects to their amounts makes sense eg
<%= bar_chart @sums_by_currency.map{|c| c.amount } %>
or if you need a name something like:
<%= bar_chart @sums_by_currency.map{|c| {name: c.unit, data: c.amount} } %>
Where unit
is whatever currency unit eg AUD
来源:https://stackoverflow.com/questions/48386920/rails-5-1-chartkick-a-sum-with-multiple-currencies