Reputation: 33755
I can't seem to get ChartKick configured properly.
What I am trying to do is to create a graph of the user's stock portfolio. The portfolio
is a model, which has_many PortStocks
each of which have a current_value
. Each PortStock
belongs to a Stock
.
My models look like this:
# == Schema Information
#
# Table name: portfolios
#
# id :bigint(8) not null, primary key
# user_id :integer
# current_dollar_value :float default(0.0)
# dollar_change :float default(0.0)
#
class Portfolio < ApplicationRecord
belongs_to :user
has_many :port_stocks
end
# == Schema Information
#
# Table name: port_stocks
#
# id :bigint(8) not null, primary key
# portfolio_id :integer
# stock_id :integer
# volume :integer
#
class PortStock < ApplicationRecord
belongs_to :portfolio
belongs_to :stock
end
# == Schema Information
#
# Table name: stocks
#
# id :bigint(8) not null, primary key
# ticker :string
# name :string
# price :float
# created_at :datetime not null
# updated_at :datetime not null
#
class Stock < ApplicationRecord
has_many :port_stocks
end
I tried the following:
<%= pie_chart @portfolio.port_stocks.group(:current_value).count %>
But that produced this pie chart:
So when I hover, it shows me the current_value
which is good but it also shows me : 1
which is weird. I want it to show me the name of each stock
, which can be accessed as port_stocks.stock.name
along with port_stocks.current_value
for that port_stock
that the stock
belongs to.
Edit 1
So I tried this:
<%= pie_chart @portfolio.port_stocks.joins(:stock).group("stocks.ticker").sum(:current_value) %>
That produces this:
That seems to work, but I would like to be able to format the current_value
as a currency (i.e. using number_to_currency(current_value)
).
Thoughts?
Upvotes: 1
Views: 327
Reputation: 33755
I figured out the correct way to do what I want:
<%= pie_chart @portfolio.port_stocks.joins(:stock).group("stocks.ticker").sum(:current_value), prefix: "$", thousands: "," %>
That produces this:
Upvotes: 2