【问题标题】:How do I get associations working right with ChartKick?如何让关联与 ChartKick 一起正常工作?
【发布时间】:2018-05-08 23:17:23
【问题描述】:

我似乎无法正确配置 ChartKick。

我要做的是创建用户股票投资组合的图表。 portfolio 是一个模型,它有_many PortStocks,每个都有一个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

我尝试了以下方法:

&lt;%= pie_chart @portfolio.port_stocks.group(:current_value).count %&gt;

但这产生了这个饼图:

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

编辑 1

所以我尝试了这个:

&lt;%= pie_chart @portfolio.port_stocks.joins(:stock).group("stocks.ticker").sum(:current_value) %&gt;

产生这个:

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

想法?

【问题讨论】:

    标签: ruby-on-rails ruby chartkick


    【解决方案1】:

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

    &lt;%= pie_chart @portfolio.port_stocks.joins(:stock).group("stocks.ticker").sum(:current_value), prefix: "$", thousands: "," %&gt;

    产生这个:

    【讨论】:

      猜你喜欢
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2018-08-23
      • 2017-02-27
      • 2021-12-27
      • 2012-07-02
      • 1970-01-01
      • 2012-07-23
      相关资源
      最近更新 更多