Is there a way in the Rails Console to print a table of database contents?
I think you should first use the hirb gem which provides a very pleasant way to print your tables columns.
- Install hirb gem:
gem install hirb
- Add this gem to your project's Gemfile:
gem 'hirb'
- Go to your project's root folder and run Rails console:
rails c
Enable hirb in the console:
require 'hirb'Hirb.enable
If you want to limit the number of rows to display, you can do:
Model.limit(n)
For instance:
User.limit(5)
You can also specify the fields that you want to display using select:
User.select("name, email").limit(5)
You can also checkout table_print, it'll work something like this:
$ gem install table_print$ rails c> require 'table_print'> tp Book.allAUTHOR | SUMMARY | TITLE-----------------------------------------------------------------------Michael Connelly | Another book by Michael Con... | The Fifth WitnessManning Mardale | From acclaimed historian Ma... | Malcolm XTina Fey | Worth it. -Trees | Bossypants
With hirb
:
require 'hirb'puts Hirb::Helpers::Table.render(ARRAY_OF_OBJECT_OR_HASHES)# Examples:puts Hirb::Helpers::Table.render([[1, "Terminator I"], [2, "Terminator II"]])+---+---------------+| 0 | 1 |+---+---------------+| 1 | Terminator I || 2 | Terminator II |+---+---------------+puts Hirb::Helpers::Table.render([{ id: 1, name: "Terminator I" }, { id: 2, name: "Terminator II" }])+----+---------------+| id | name |+----+---------------+| 1 | Terminator I || 2 | Terminator II |+----+---------------+# specifying the order of the fieldsputs Hirb::Helpers::Table.render([{ id: 1, name: "Terminator I" }, { id: 2, name: "Terminator II" }], fields: [:name, :id])+---------------+----+| name | id |+---------------+----+| Terminator I | 1 || Terminator II | 2 |+---------------+----+