简体   繁体   中英

Deleting records using Mongomapper in Rails

I'm enjoying the pretty amazing MongoDB in Rails by using Mongomapper but I am having problems removing records.

What is the accepted way of removing records, and also removing a whole document?

I tried using Stuff.destroy_all but it seems to crash the web server.

Sorry, that's not well documented. I'm opening an issue for that.

See the class methods and instance methods .

my_doc.destroy    # fires callbacks
my_doc.delete     # no callbacks, just removes it from the database
MyDoc.destroy_all # fires callbacks, shouldn't crash...!
MyDoc.delete_all  # no callbacks
MyDoc.destroy("b965105ea203368234636df2", "368234636df21c64f05358a4")
MyDoc.delete("b965105ea203368234636df2", "368234636df21c64f05358a4")

Yea, I have stumbled and bumbled quite a few times deleting stuff in MongoMapper. This technique seems to work as well:

MessageLog.destroy_all(:created_at.gte => @start_time)

Took me a while to figure out why delete_all was sooooo much faster than destroy_all :-p

And delete_all and destroy_all also work as Plucky methods, so you can do things like:

MyDoc.where(status: 'unneeded').delete_all
MyDoc.where(status: 'unneeded').destroy_all

Depending on if you want to avoid callbacks ( delete_all ) or execute them ( destroy_all ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM