I have this code in a model for an invoicing app. This virtual attribute current_invoice
gets the only non-rescinded invoice associated with a contract. The code works but it seems really verbose. Can this be done in a prettier way?
def current_invoice
result = []
invoices.each do |i|
if i.current_status != "rescinded"
result.push(i)
else
false
end
end
if result.length > 1
raise "Only one non-rescinded invoice association per contract"
else
result[0]
end
end
You might be wondering why not just do this...
invoices.where.not(current_status: "rescinded").first
...but current_status is a virtual attribute on invoice.