0

我想为一个模型做一个 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 记录。

4

1 回答 1

0

更改 LoanApplication 模型:

has_many :applicant_co_applicants, -> { not_deleted }

将此添加到ApplicantCoApplicant模型中:

scope :not_deleted, -> { where.not('deleted_at' => nil) }
于 2017-07-24T08:43:41.837 回答