jhrs21
jhrs21

Reputation: 391

Create or increment a field in Mongoid with Rails 4

I have a model like this:

class Invoice
  include Mongoid::Document
  field :local, type: String
  field :date, type: DateTime
  field :total, type: Float
end

class LogInvoice
  include Mongoid::Document
  field :date, type: Date
  field :local, type: String
  field :summary, type: Hash
end

The field summary is a Hash like this:

summary = {invoices : 0, amount : 0.0}

For each invoice stored, I must create an LogInvoice for that day with total number of Invoice (count of Invoice) in LogInvoice.summary[:invoices] and with the total ammount of money (summatory of Invoice.total) in LogInvoice.summary[:amount]

If the Invoice exist I must to update the LogInvoice of that day.

I can't know if a object existe because LogInvoice.find() returns an exception if it doesn't, so how can I update an existing object LogInvoice or created if it doesn't?

Thank you

Upvotes: 1

Views: 1372

Answers (1)

Enrique Fueyo
Enrique Fueyo

Reputation: 3488

If I've understood your question you should do something like this:

my_invoice_criteria = Invoice.all # or Invoice.where date: the_date_I_want or anything else
my_invoice_criteria.each do |invoice|
 log_invoice = LogInvoice.find_or_create_by date: invoice.obtain_proper_date
 #Use this for atomic persistence
 log_invoice.inc :"summary.invoices" => 1
 log_invoice.inc :"summary.amount" => invoice.total
 #Use this for standard persistence
 log_invoice.summary[:invoices]+=1
 log_invoice.summary[:amount]+=invoice.total
 log_invoice.save
end

Ref: Atomic persistence Docs Standard persistence Docs

Upvotes: 1

Related Questions