Rails Console Tips & Tricks

Igor Kasyanchuk
Dec 9, 2023 • 2 minutes read

Rails Console

  • Rails console Sandbox

    Be very careful using this on production, when you have site visitors because it’s wrapping all changes in the transaction and blocking execution. More details here.

    Any modifications you make will be rolled back on exit

    > rails c --sandbox
    Specially when connecting with production console directly, 
    it's a good idea to connect as sandbox so you don't change anything accidentally
    > rails console -e production
    
  • app object in the rails console

    There is an "app" object in rails console that can be used for multiple useful things like

    1. access application routers app.admin_ox_packaging_rules_path
    2. testing out or hitting controller methods directly from console app.get app.admin_ox_packaging_rules_path or app.get("api/v1/shipments")
  • helper object in the rails console

    Similar, to app object there is a "helper" object that can be used for accessing view helper methods

    helper.number_to_currency(50.5)

  • skip printing out big results in the console

    When you want to skip printing out big results in the console (which can be extremely slow especially in SSH sessions). You can append a ; nil to the line. For example: users = User.all.to_a; nil This way users will get assigned with the array and the array won't be printed out to STDOUT as usual.

  • useful shortcuts for console

    1. Option + arrow keys (left/right) => Move the cursor one word at a time
    2. Ctrl + a => Move the cursor at the end of line
    3. Ctrl + e => Move the cursor at the start of line
  • print SQL logs into Rails console

    ActiveRecord::Base.logger = Logger.new(STDOUT)

  • print something on Rails console start

    Sometimes ENVs from previous rails console run are kept on new console run Or you can just forget that you set DATABASE_URL to production one via .env

    It could be useful to print something on rails console start (e.g. to avoid doing some mess on production 😬) It can simply be done by adding .pryrc file with something like that:

    Pry.config.exec_string = puts "\\nDATABASE_URL=#{ENV["DATABASE_URL"]}\\n"

Useful gems

See all