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 consoleThere is an "app" object in rails console that can be used for multiple useful things like
- access application routers
app.admin_ox_packaging_rules_path
- testing out or hitting controller methods directly from console
app.get app.admin_ox_packaging_rules_path
orapp.get("api/v1/shipments")
- access application routers
-
helper
object in the rails consoleSimilar, 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
- Option + arrow keys (left/right) => Move the cursor one word at a time
- Ctrl + a => Move the cursor at the end of line
- 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"