5 Rails console tricks

The Ruby on Rails console (REPL) is a useful tool for quickly exploring code or testing ideas.
Below the 5 most helpful tricks are described in more detail.

1. App

After the console was started, the variable app is immediately available. It contains a ActionDispatch::Integration::Session object, which makes the Rails application more approachable in the REPL. For example triggering requests:

app.get app.articles_path
# => 200

And the response of the last request:

app.response.body
# => "<!DOCTYPE html>\n<html lang=\"de\">\n  <head> ..."

2. Helper

All Rails Helper are available in the console as well:

helper.link_to 'All articles', app.articles_path
# => "<a href=\"/articles\">All articles</a>"

3. Last expression

The last statements result is always accessable via the variable _:

Article.last
# => #<Article:0x00000004396418> { :id => 78, ... }
_
# => #<Article:0x00000004396418> { :id => 78, ... }
1
# =>
_
# => 1

4. Default Object in sub IRB

By default, the console context is main:

article = Article.last
article.title
# => "5 Rails Konsole Tips"

With irb it can be moved to an object.

irb Article.last
title
# => "5 Rails Konsole Tips"

In the so-called sub IRB, all methods of the object can be accessed directly without naming the message receiver.
After leaving the sub IRB, one is back in the main context again:

exit
=> #<IRB::Irb: @context=#<IRB::Context:0x000000108178f0> ... >
title
# => NameError: undefined local variable or method `title' for main:Object

Of course, the sub IRB can be moved into app too:

irb app
get app.article_path(Article.last)
# => 200

5. Rollback data with sandbox

When debugging data, it may be necessary to manipulate it. Or an operation must be executed to detect an error. Restoring this data for further trials can be cumbersome.
Then the REPL should be started in a sandbox:

rails console production --sandbox

After executing the data operations:

article = Article.find 1
# => #<Article:0x00000004143cd8>
article.delete
# => DELETE FROM "articles" WHERE "articles"."id" = $1 [["id", 1]]
Article.find 1
# => ActiveRecord::RecordNotFound: Couldn't find Article with 'id'=1

After exiting the console, a rollback is automatically executed, which rolls back all data changes:

exit
# => ROLLBACK

Then the data is in its original state again:

# rails console production
article = Article.find 1
# => #<Article:0x00000003db3848>