[Rails concerns] Stop putting code into your ApplicationController!!

Sometimes people put too much stuff at the application controller, and they make all the others controllers inherit from it.

This is not a good pratice, since you can end up loading unnecessary helpers or whole gems at your API controllers for example, and losing performance.


Let’s say, for example, that every user at your application has a integer field called¬†visits,¬†and it gets incremented every time the user visits a page. If you would have that in your application controller, it should look something like this:


Instead, you should extract specific functionalities to concerns and include them where and when you need it, letting the application controller as skinny as possible.


Now you can include this code in every controller we need, making it more organized and explicit:




Mongoid: connecting to two databases


Let’s say you have two collections at your Ruby on Rails application, users and urls. Now you want to save the users collection in one server, and the urls collection in another one.


First, add the second server configuration at config/mongoid.yml, as following:

Now you have a default client connection to the first server and have a second one called “secondary” to the other.

The other thing you need to do, is to tell your collection what client it should use. The users collection will use the default configuration, rails has that covered for us.

For the urls collection, your model should look like this:


Sharded mongodb

If your secondary database is actually sharded across two or more servers, you need to list all the servers ips at mongoid.yml file and set the connection option to sharded:

And don’t forget to include the shard key at the url model:

All done, happy deploy!