【问题标题】:Can I use has_many through: without destroying all associated records on delete?我可以使用 has_many through: 在删除时不破坏所有关联记录吗?
【发布时间】:2015-07-10 02:26:40
【问题描述】:

我正在尝试列出commissions 以添加到申请者委员会。

ApplicantCommission.rb
  belongs_to :applicant
  belongs_to :commission

Applicant.rb

  has_many :applicant_commissions

Commission.rb

  has_many :applicant_commissions

问题是,如果我通过以下方式使用 has_many:当我删除申请人时,佣金也会被删除。 (反之亦然)

有什么建议我可以在不丢失相关记录的情况下创建和销毁它吗?

【问题讨论】:

  • 您的问题中没有has_many :through
  • 我一直这样做,并且从不丢失相关记录。删除申请人(或佣金)时唯一应该删除的是关联记录(ApplicantCommission)
  • 我正在使用 rails_admin 删除它们。也许这是一个问题?

标签: ruby-on-rails ruby-on-rails-4 has-many-through


【解决方案1】:

你的文件中应该有以下关系

ApplicantCommission.rb

belongs_to :applicant
belongs_to :commission

申请人.rb

has_many :applicant_commissions,  dependent: :destroy
has_many :commissions, through: :applicant_commissions

佣金.rb

has_many :applicant_commissions,  dependent: :destroy
has_many :applications, through: :applicant_commissions

这样您的关联就不会被删除。 其次,我建议您查看此“mark_for_destruction”以进行删除。 这将帮助您轻松删除内容。

http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html

【讨论】:

    猜你喜欢
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    相关资源
    最近更新 更多