我如何让关联与 ChartKick 一起正常工作?

How do I get associations working right with ChartKick?

我似乎无法正确配置 ChartKick。

我想做的是创建用户股票投资组合的图表。 portfolio是一个模型,其中has_manyPortStocks每个都有一个current_value。每个PortStock属于一个Stock.

我的模型是这样的:

# == 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

我尝试了以下方法:

<%= pie_chart @portfolio.port_stocks.group(:current_value).count %>

但这产生了这个饼图:

因此,当我悬停时,它会向我显示 current_value,这很好,但它也会向我显示 : 1,这很奇怪。我希望它向我显示每个 stock 的名称,可以通过 port_stocks.stock.nameport_stocks.current_value 访问 stock 所属的 port_stock

编辑 1

所以我尝试了这个:

<%= pie_chart @portfolio.port_stocks.joins(:stock).group("stocks.ticker").sum(:current_value) %>

产生这个:

这似乎可行,但我希望能够将 current_value 格式化为货币(即使用 number_to_currency(current_value))。

想法?

我找到了做我想做的事情的正确方法:

<%= pie_chart @portfolio.port_stocks.joins(:stock).group("stocks.ticker").sum(:current_value), prefix: "$", thousands: "," %>

产生这个: