[英]How do I get associations working right with ChartKick?
I can't seem to get ChartKick configured properly. 我似乎无法正确配置ChartKick。
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
. portfolio
是一个模型,它具有多个PortStocks
每个PortStocks
都有一个current_value
。 Each PortStock
belongs to a Stock
. 每个
PortStock
属于一个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. 因此,当我将鼠标悬停时,它显示的
current_value
很好,但同时也显示了: 1
这很奇怪。 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. 我想让它显示我的每名
stock
,可以作为访问port_stocks.stock.name
沿port_stocks.current_value
为port_stock
该stock
所属。
Edit 1 编辑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 (ie using number_to_currency(current_value)
). 这似乎可行,但是我希望能够将
current_value
格式化为货币(即,使用number_to_currency(current_value)
)。
Thoughts? 有什么想法吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.