lundi 6 juillet 2015

FIND Highest Value From Table

I want to increment tax_invoice_number each time when record is created. The pattern of tax_invoice_number saved is in this form "IN2015-000001". when new record is created it should be "IN2015-000002".

Scenario 1:

key = "IN2015"

max = TaxInvoice.where("tax_invoice_number like ?", "%#{key}%").max_by(&:tax_invoice_number)

unless max.nil?
  increment = max.tax_invoice_number.split('-')[-1].to_i + 1
else
  increment = "000001"   #For First Record
end

tax_invoice_number = key + "-" + (sprintf "%06d",increment)

While doing this i found one problem that is if suppose i have two tax_invoice_numbers i,e "IN2015-999999" and "IN2015-1000000" and when i do above operation i get max = "IN2015-999999" #which should not be as "IN2015-1000000" is greater, as we are saving tax_invoice_number as string "IN2015-999999" is greater.

So to avoid that

Scenario 2

key = "IN2015"

max = TaxInvoice.where("tax_invoice_number like ?", "%#{key}%").map{|x| x.tax_invoice_number.split('-').last.to_i }.max

unless max.nil?
  increment = max + 1
else
  increment = "000001"   #For First Record
end

tax_invoice_number = key + "-" + (sprintf "%06d",increment)

Here i am getting correct output no problem.

Is there any better solution like:

TaxInvoice.maximum("tax_invoice_number")

I cant do this as my tax_invoice_number is string in table and i cant change my migration. If i do this TaxInvoice.maximum("tax_invoice_number") again this "IN2015-999999" will come maximum then "IN2015-1000000"

Aucun commentaire:

Enregistrer un commentaire