Rails Console – a few tips you may not have known

Tram Ho

For a Ruby on Rails developer, the Rails console is probably a familiar and indispensable tool in product development. The console helps interact with Rails applications, especially models, in real-time environments. Let’s take a look at some tips to help us use rails console more effectively.


The Rails console has a mode called “sandbox”. In this mode, all changes to the database will be restored when you exit the session.

This is a great mode for you to freely test, update without affecting the data.

Get the value of the just-performed expression

Assuming you open the rails console:

The result is the first 10 job records. If you want to get this value you just need

And then can use comfortably:

Or you can use “_” directly

Search method with grep

You can look up the method name of an object if you remember part of its name. By using grep:

Find out where the method is declared

The source_location method of the Object class returns the full path where the method is declared. The results returned include the path to the file and the code that the method is declared. This method is especially useful when we want to dig into a 3rd party library

Returns the source code of a method

Above we know how to determine the exact location of a method. But we can even see its source code. This can be done via the object’s source method:

App object

The console provides an interesting object, which is the app object . This is basically your miniature app. With this object, we can interact with the application as an HTTP client:

  • GET

  • Search for paths with game routers

  • Along a lot of interesting things you can explore
Chia sẻ bài viết ngay

Nguồn bài viết : Viblo