Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple boolean data update with mongdb?

I am using Rails and mongoid to work with mongodb.

Usually in rails when working with Active:Record, you have access to the method .toggle! which simply allows you to invert the value of a boolean field in your db.

Unfortunately this method is not available for mongoDB:

user = User.first
user.toggle!(:admin)
NoMethodError: undefined method `toggle!' for #<User:0x00000100eee700>

This is unfortunate... and stupidly enough I don't see how to get around without some complicated code...

Any suggestion on how to achieve the same result concisely ?

Thanks,

Alex

ps: also one of the problems is that when I want to modify the field, it goes through validation again... and it's asking for the :password which I don't save in the db, so:

User.first.admin = !User.first.admin

won't even work :(

like image 529
Alex Avatar asked Jan 16 '11 05:01

Alex


1 Answers

The issue here is specifically mongoid, not mongodb. toggle! is a part of ActiveRecord::Base, but fortunately it's not hard to replicate.

def toggle!(field)
  send "#{field}=", !self.send("#{field}?")
  save :validation => false
end

Add that into your model (or add it into a module, and include it in your model), and your Mongoid models will gain functionality equivalent to what you're used to in AR. It will read the field's value, invert it, write it (through the setter, per the toggle! documentation), and then save the document, bypassing validation.

like image 116
Chris Heald Avatar answered Oct 10 '22 09:10

Chris Heald