Introducing Rails console

Rails console is a command line program for interacting with the Rails applications. It has the full power of the Ruby language and Rails environment. We can start the Rails console using the following command.

1bundle exec rails console
1Running via Spring preloader in process 71028
2Loading development environment (Rails 6.0.3.4)
3irb(main):001:0>

Let's run some commands to see how Rails console can help us get some useful information.

Task.column_names

Task.column_names returns the names of all the columns of tasks table.

1irb(main):003:0> Task.column_names
2=> ["id", "title", "created_at", "updated_at"]

Notice that we have a column named id present. Rails adds this column by default and it serves as the primary key of the table. The value of the id auto increments when a new record is created. We will see it in action shortly.

Task.count

Task.count returns the number of records in the table.

1irb(main):002:0> Task.count
2   (0.1ms)  SELECT COUNT(*) FROM "tasks"
3=> 0

It means right now we do not have any record in the Tasks table.

Task.create

Task.create creates and saves a new task in the database.

1irb(main):004:0> Task.create
2   (0.3ms)  begin transaction
3  SQL (2.8ms)  INSERT INTO "tasks" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2019-01-28 17:00:26.379031"], ["updated_at", "2019-01-28 17:00:26.379031"]]
4   (11.7ms)  commit transaction
5=> #<Task id: 1, title: nil, created_at: "2019-01-28 17:00:26", updated_at: "2019-01-28 17:00:26">

Notice that the id is 1. If we create one more task then the id of the new task will be 2.

We can exit the Rails console by typing exit.

Clearing the console

On Mac we can use Command + K. On Linux we can use Ctrl + l.

Reloading the console

To reload the console we can use the reload! command.

1>> reload!
2Reloading...
3=> true

Without this functionality one may want to exit the console and start it to reflect the changes in the code.

Getting value of the last expression

Say we write some query into the console and forget to assign it to a variable, we can use the special underscore(_) to retrieve the value.

12.7.0 :008 > Task.find(1)
2  Task Load (0.3ms)  SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
3 => #<Task id: 1, title: "My first task", created_at: "2020-03-30 08:55:09", updated_at: "2020-04-03 09:01:42">
42.7.0 :009 > _
5 => #<Task id: 1, title: "My first task", created_at: "2020-03-30 08:55:09", updated_at: "2020-04-03 09:01:42">
6

We can see in the above example we are using the _ to access the last expressions value.

Use c for shortcut

Rails console can be started by either of the following two commands.

1bundle exec rails console
1bundle exec rails c

Switching the environment

Rails console can be started in staging or in production mode like this.

1bundle exec rails console -e production
2bundle exec rails console -e staging

When we do bundle exec rails console then it is equivalent to the followings.

1bundle exec rails console -e development

Command History

If we want to re-execute a previously executed command then we can have two options.

We can use the up and down arrow to get to the previously typed command.

We can also use ctrl+r to search the previously history just like it can be done on bash shell.

Use source_location for to know the location of the code

If we want to know where a method is defined then we can use source_location to find that.

We know that Task models have save method because of Active Record. Let's find out where this save method is defined.

1>> Task.first.method(:save).source_location
2==> ["/Users/raj.singh/.rbenv/versions/2.7.2/lib/ruby/gems/2.7.0/gems/activerecord-6.0.3.4/lib/active_record/suppressor.rb", 43]

User helper

Rails makes helper methods available to console.

1>> helper.number_to_currency(10)
2==> "$10.00"
3
4>> helper.time_ago_in_words(Time.now)
5=> "less than a minute"

Working in a sandbox

When we open console and if we make any changes to the database then those changes are permanent. However sometimes we want to test something and we want all those changes to rollback when we exit console. This is very often used in debugging in production environment.

1bundle exec rails console -e production --sandbox
2Loading production environment in sandbox
3Any modifications you make will be rolled back on exit
4>> Task.update_all(name: "new name")
5>> exit

Once we exit then all the task name we had changed would be rolled back.

Use exit to quit console

1irb(main):001:0> exit

Simple prompt

By default when console starts then prompt like this.

1$ bundle exec rails console
2Running via Spring preloader in process 77597
3Loading development environment (Rails 6.0.3.4)
4irb(main):001:0> a = 1
5irb(main):002:0> b = 2
6irb(main):003:0> c = 3

We can also ask console to have simple prompt.

1$ bundle exec rails console -- --simple-prompt
2Running via Spring preloader in process 77680
3Loading development environment (Rails 6.0.3.4)
4>> a = 1
5>> b = 2
6>> c = 3

Have fun with app

In console just type app and scroll through all it prints. You will learn a thing or two.

1>> app
1>> app.cookies
2>> app.get(app.root_path)
3>> app.get('/books/2')

There is nothing to commit in this chapter since all we had done was work in the Rails console.