【问题标题】:has_many association for only soft deleted recordshas_many 仅用于软删除记录的关联
【发布时间】:2017-07-24 17:27:36
【问题描述】:

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

【问题讨论】:

  • 你能显示你尝试过的查询吗?

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


【解决方案1】:

更改 LoanApplication 模型:

has_many :applicant_co_applicants, -> { not_deleted }

将此添加到申请人CoApplicant 模型中:

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

【讨论】:

  • 这并不能完全解决我的问题,但感谢您的帮助。
  • @KingsleySimon 我做了一些小改动。你现在得到了什么结果?
  • 现在结果如何?
  • 我不得不将它切换到 has_many :applicant_co_applicants, -> { not_deleted }, :class_name => "ApplicantCoApplicant", :foreign_key => "loan_application_id"。您的选项返回错误,即使像这样运行它,它仍然返回空
猜你喜欢
  • 2012-05-13
  • 2017-09-23
  • 1970-01-01
  • 2013-05-30
  • 2019-08-07
  • 1970-01-01
  • 2012-10-24
  • 2017-05-19
  • 1970-01-01
相关资源
最近更新 更多