如何维护已删除对象的关联?

时间:2018-07-05 01:19:15

标签: ruby-on-rails ruby-on-rails-5 associations

我有一个对象PortStock,我通过OrderHistory来跟踪。即,每次对port_stock对象执行特定操作时,我都会创建一个与该order_history关联的port_stock对象。

OrderHistory视为该特定PortStock上的交易历史。

现在的问题是,当我删除PortStock对象时,我仍然希望能够检索(并显示)与该order_history记录关联的所有PortStock对象。 / p>

这是我当前的操作方式,当删除@port_stock时不起作用:

@port_stock = current_user.port_stocks.friendly.find(params[:id])
@stock = @port_stock.stock
@order_histories = OrderHistory.joins(:port_stock).where(port_stocks: { ticker: @stock.ticker}).group_by { |o| o.port_stock }

有想法吗?

编辑1

我的PortStock模型如下:

# == Schema Information
#
# Table name: port_stocks
#
#  id                :bigint(8)        not null, primary key
#  portfolio_id      :integer
#  stock_id          :integer
#  volume            :integer
#  action            :integer
#  position          :integer          default("open")
#  ticker            :string
#

class PortStock < ApplicationRecord
  extend FriendlyId
  friendly_id :ticker
  belongs_to :portfolio
  belongs_to :stock
  has_many :order_histories

  enum action: [ :buy, :sell ]
  enum position: [ :open, :closed ]
end

我的OrderHistory模型如下:

# == Schema Information
#
# Table name: order_histories
#
#  id                :bigint(8)        not null, primary key
#  port_stock_id     :integer
#  num_units         :integer
#  action            :integer
#  created_at        :datetime         not null
#  updated_at        :datetime         not null
#

class OrderHistory < ApplicationRecord
  belongs_to :port_stock
  enum action: [ :buy, :sell ]
end

0 个答案:

没有答案