Home > OS >  how can I create child model conditions on ActiveRecord
how can I create child model conditions on ActiveRecord

Time:09-24

class Invoice < ApplicationRecord
  belongs_to :purchase
end

class Purchase < ApplicationRecord
  has_many   :invoices
end


Invoice has, boolean "paid" columns.

since it has_many, sometime invoice record may be more than 1. I would like to search "all paid", or "partial paid", or "not paid" purchase record. if invoice records are 3, one of them is paid, it means "partial paid"

how could I make this condition with ApplicationRecord?

I tried like this

joins(:invoices).where("invoices.paid": true)

but it also returns partial paid records.

CodePudding user response:

I think i solved by myself

paid   = joins(:invoices).where(invoices: {status: true}).pluck(:id)
unpaid = joins(:invoices).where(invoices: {status: false}).pluck(:id)

#return paid
where(id: paid - unpaid)

#return unpaid
where(id: unpaid - paid)

#return partial paid
where(id: paid & unpaid)

CodePudding user response:

Since paid is a boolean field here, it holds either true or false value.

If you have another field(probably payment_status) in Invoice table that should identify the record as "Fully Paid", "Partially Paid", "Not Paid". Then the query would be:

Purchase.joins(:invoice).where(invoices: {paid: true, payment_status: "Fully Paid"})  # `paid: true` could be omitted

As a best practice you can define a scope:

class Purchase < ApplicationRecord
  has_many :invoices
  scope    :paid_invoices, -> { joins(:invoice).where(invoices: {payment_status: "Fully Paid"}) }
end
  • Related