esmanbo
esmanbo

Reputation: 11

how can I create child model conditions on ActiveRecord

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.

Upvotes: 0

Views: 67

Answers (1)

Manjunath P
Manjunath P

Reputation: 433

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

Upvotes: 0

Related Questions