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
Advertisements
This entry was posted in General. Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s