Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in the Rails Console to print a table of database contents?

I'm looking for a clean and simple way to print in the Rails Console the contents of my 5 row database with 2 columns.

Any ideas? I Googled around but didn't find much.

like image 573
Zack Shapiro Avatar asked May 05 '12 18:05

Zack Shapiro


2 Answers

I think you should first use the hirb gem which provides a very pleasant way to print your tables columns.

  1. Install hirb gem: gem install hirb
  2. Add this gem to your project's Gemfile: gem 'hirb'
  3. Go to your project's root folder and run Rails console: rails c
  4. 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)
like image 62
Amokrane Chentir Avatar answered Nov 13 '22 03:11

Amokrane Chentir


You can also checkout table_print, it'll work something like this:

$ gem install table_print
$ rails c
> require 'table_print'
> tp Book.all
AUTHOR            | SUMMARY                         | TITLE
-----------------------------------------------------------------------
Michael Connelly  | Another book by Michael Con...  | The Fifth Witness
Manning Mardale   | From acclaimed historian Ma...  | Malcolm X
Tina Fey          | Worth it. -Trees                | Bossypants
like image 30
Chris Doyle Avatar answered Nov 13 '22 04:11

Chris Doyle