Rails console cheatsheet

Updated: 

Boost your Rails productivity with our comprehensive console cheatsheet. Learn essential commands and tips from the Full Stack Rails Mastery course.

This lesson is from Full Stack Rails Mastery.

Use reload! to reload your code changes

After making changes to your code, use reload! in the console to load the latest version without restarting the console.

Access the last executed command's result with _

The underscore variable stores the result of the last executed command.

 > x = 1 => 1 > _ => 1 

Search command history with Ctrl + R

(reverse-i-search)`x'x = 1

Toggle SQL logging 

 ActiveRecord::Base.logger.level = 1 

Switch between the default 0 (log SQL) and 1 (silence SQL) to control query logging.

Access Rails view helpers with helper:

 > helper.time_ago_in_words(3.days.ago) => "3 days" > helper.link_to("Products", app.products_path) => "<a href=\"/products\">Products</a>" 

Use app to access the Rails application context

 > app.root_path  => "/"  

Sandbox your console session

Start console with  --sandbox to rollback all database changes when you exit.

 rails console --sandbox 

Access consoles for different environments

By default, Rails loads the development environment. But you can access the production environment console like this:

 rails console -e production 

And test like this:

 rails console -e test 

Use puts for cleaner output

 puts User.pluck(:email) 

gives a cleaner output than just 

 User.pluck(:email) 

Clear the console

Use Ctrl + L or Cmd + K on Mac and Linux.

Use system(cls) on Windows