has_many关联仅用于软删除的记录

时间:2017-07-24 08:29:51

标签: ruby-on-rails activerecord acts-as-paranoid

我想为一个模型做一个has_many关联,该模型有一些记录,其中deleted_at不是nil,我希望能够只通过has_many关联检索这些记录,但目前它不能正常工作,我不知道如何解决它。

class LoanApplication < ActiveRecord::Base
  acts_as_paranoid
  has_many :applicant_co_applicants, :class_name => "ApplicantCoApplicant", :foreign_key => "loan_application_id"
  has_many :co_applicant_infos, :through => :applicant_co_applicants, :source => :loan_application_co_applicant, :dependent => :destroy
  has_many :removed_co_applicant_infos, :through => :applicant_co_applicants, :source => :loan_application_co_applicant, :dependent => :destroy
end

class ApplicantCoApplicant < ActiveRecord::Base
  acts_as_paranoid
  attr_accessible :loan_application_id, :co_applicant_id, :deleted_at

  belongs_to :loan_application_co_applicant, class_name: 'LoanApplication', foreign_key: "co_applicant_id"
  belongs_to :loan_application, class_name: 'LoanApplication', foreign_key: "loan_application_id"
end

我试图只检索ApplicationCoApplicant表中soft_deleted记录的loan_application对象,但我的查询仍然只搜索带有deleted_at的记录:nil而不是deleted_at!= nil

有什么方法我只能从ApplicantCoAppliant模型中获取soft_deleted记录并使用它来过滤co_applicant_infos关联?

非常感谢

**LoanApplication Table** 
id     name    deleted_at
1   person a        nil
2   co person b     nil
3   co person c     nil

**ApplicantCoApplicant Table**
  id     loan_application_id     co_applicant_id   deleted_at
  1          1                       2               nil
  2          1                       3               2017-07-24 02:34:37

这是我的样本表。我想要一个has_many关联,当我打电话时 LoanApplication.find(1).removed_co_applicant_infos,它只会返回ID为3的LoanApplication记录。

1 个答案:

答案 0 :(得分:0)

更改LoanApplication模型:

has_many :applicant_co_applicants, -> { not_deleted }

将此添加到ApplicantCoApplicant模型:

scope :not_deleted, -> { where.not('deleted_at' => nil) }