Larry Price
Larry Price

Reputation: 439

Mongoid 3.1 Querying Syntax Issue in Ruby 1.9.3

I have a Ruby Association class as follows:

class Association
  include Mongoid::Document
  field :issued, type: Integer
  field :lifetime, type: Integer
end

And I want to delete all of the docs in my collection where doc.issued + doc.lifetime > Time.now. I found the following syntax on the web:

Association.delete_all(["issued + lifetime > ?", Time.now.to_i])

I can't get this to work and I get the following error:

TypeError: can't convert Symbol into Integer
    from /var/lib/gems/1.9.1/gems/mongoid-3.1.0/lib/mongoid/persistence.rb:298:in `[]'
    from /var/lib/gems/1.9.1/gems/mongoid-3.1.0/lib/mongoid/persistence.rb:298:in `delete_all'
    from (irb):77
    from /usr/bin/irb:12:in `<main>'

Can someone tell me what's wrong with this syntax or suggest different syntax that will work?

Upvotes: 0

Views: 146

Answers (1)

Aymeric
Aymeric

Reputation: 906

delete_all, like where, needs a list of conditions on single fields, like :

Association.delete_all(issued: 10)

In your case, you can use Javascript.

Association.for_js("(this.issued + this.lifetime) > ti", ti: Time.now.to_i).delete_all

Note : the performance won't be excellent, because the condition will be tested on each document.

Upvotes: 1

Related Questions