Skip to content

Rails Console in the Browser (on-demand)

Why in the browser?

While doing some research and working on some details for my new book Realtime Rails, I came across an issue where making changes to ActiveRecord objects in the terminal’s rails console were not showing up in the web browser. When working in development, based on default settings for ActionCable and the Rails server, for the broadcast to show up, it needs to be using the same process instead of the separate process spaned by the rails console in the terminal.

Also, having the console show up in the browser on demand is a pretty cool setup. You can see the changes in real time and interact with the objects in the browser.

How to set it up

If you need to set up the Rails console in the browser yourself instead, you will need to add the web-console gem to your Gemfile:

gem 'web-console', group: :development

Then, run bundle install to install the gem.

Once installed, you can add a web console to any view file by adding <%= console %>, then interact with the Rails console in the browser.

Taking it a step further

If you want to add some convenience to this process, you can add route, controller, and view (that are development only) to have the browser show up in the browser on a specific page in your application.

First, adding the development-only route:

if Rails.env.development?
get '/console', to: 'console#show'
end

Then, create the controller:

class ConsoleController < ApplicationController
def show
end
end

And finally, the view:

<h1>Rails Console</h1>
<%= console %>

Now, when you visit /console in your development environment, you will have a console in the browser.

Alternate Idea

Another idea is to add a link to the console in your application’s footer. This way, you can easily access the console from any page in your application.

Then, add the link to the console in your application.html.erb layout file, but since we’re not relying on the route to show the console in the development environment only, we will need to add a conditional check in the template:

<% if Rails.env.development? %>
<%= console %>
<% end %>

Personally, I’d rather have the console appear on a specific page, but this is a good alternative if you want the console available on every page in your application.