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

I'm looking for a clean and easy way to print the contents of my 5-row, two-column database into the Rails Console.

Any ideas? I googled around but did not find much.

+4
source share
4 answers

I think you should use hirb gem first, which provides a very nice way to print table columns.

  • Install hirb gem: gem install hirb
  • Add this stone to your Gemfile project: gem 'hirb'
  • Go to the project root folder and launch the Rails console: rails c
  • Enable hirb in console:

     require 'hirb' Hirb.enable 

If you want to limit the number of lines displayed, 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) 
+12
source

You can also check table_print , it will 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 
+5
source

Yes. Check out the hirb gem. It is also worth trying wirble and awesome_print .

+1
source

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 fields puts 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 | +---------------+----+ 
0
source

Source: https://habr.com/ru/post/1410893/


All Articles