8

我正在寻找一种干净简单的方法来在 Rails 控制台中打印我的 5 行数据库的内容,其中包含 2 列。

有任何想法吗?我用谷歌搜索,但没有找到太多。

4

4 回答 4

17

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)
于 2012-05-05T18:25:46.650 回答
7

您也可以结帐table_print,它会像这样工作:

$ 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
于 2013-09-25T19:00:46.197 回答
2

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  |
+---------------+----+
于 2017-03-01T23:04:16.070 回答
1

Yes. Check out hirb gem. Also worth trying is wirble and awesome_print.

于 2012-05-05T18:24:51.813 回答