RoR Tips & Tricks Series – #1

I am staring this series of blog posts. This will cover few tips and / or tricks from ROR. We as developer come across a situation, where we struggle to solve the problem. Once solved we realise that, in our trial and error efforts we have found some trick, which is not documented.

This blog post is an effort to  collect such tips and tricks and make developers life easy !!!

Tip : .first and .last returns same object on mongoid 5

Database : Mongodb

There are 2 ways to overcome this problem.

Simple query that comes in mind is to use “all[-1]”. But this is expensive. Instead use order to get last document. Here is the benchmark of both queries. Collection used for this benchmark has size as 35783 documents.

Benchmark.ms { Unit.all[-1] }
    => 5881.32297800621
Benchmark.ms { Unit.desc(:id).first }
    => 3.993231992353685

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.