There are many times where I find myself typing the same scripts and queries in the Rails console. Thankfully it's possible to add helper methods to the console. For example, on the DailySmarty application I constantly was performing user queries to test out new features. Sometimes I would run a query based on an email to search for a specific user, while sometimes I simply wanted any user. So it was very common that I was writing console queries such as:
> u = User.find_by_email('email@example.com')
> u = User.last
Not a big deal? No, not really, but we can do better. I created a new file in the lib directory called console_helper.rb with the following code modules:
This will create a method that allows me to simply type u if I want the last user or u('firstname.lastname@example.org') if I want a specific user. Which is pretty awesome. Now we simply need to add it to the config/application.rb file so that Rails knows about it with the following code:
You can see the full application.rb file here if you'd like some context.
And now when I open up the Rails console I can run the following queries:
Credit to Brandon Keepers