Kingsley Simon
Kingsley Simon

Reputation: 2210

has_many association for only soft deleted records

I want to do a has_many association for a model that has some records with deleted_at not nil and i want to be able to only retrieve those records via a has_many association but currently it is not working and i am not sure how to fix it.

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

I tried to retrieve only the loan_application objects of soft_deleted records in the ApplicationCoApplicant table but my query still searched only for records with deleted_at: nil instead of deleted_at != nil

Is there any way i can only get the soft_deleted records from the ApplicantCoAppliant model and use that to filter the co_applicant_infos association?

Thanks much appreciated

**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

This is my sample Table. I want to a has_many associated whereby when i call LoanApplication.find(1).removed_co_applicant_infos, it will return only the record of LoanApplication with id 3.

Upvotes: 0

Views: 765

Answers (1)

Sajin
Sajin

Reputation: 1638

change LoanApplication model:

has_many :applicant_co_applicants, -> { not_deleted }

add this to ApplicantCoApplicant model:

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

Upvotes: 1

Related Questions