Skip to content

Rendering a Query as a Table

Daniel Vandersluis edited this page Apr 5, 2014 · 2 revisions

Note: The code demonstrated on this page is available as part of the compendium_demo project, which you can clone and play with yourself. This sample application gives a simple report outlining spending over a given period.

A table is in general a straight render of all the data present in the query results. The order of columns in your table is dependent on the order of columns in the query (and as such, it is helpful to explicitly select the columns you want in the order you want when building your query).

Tables can be rendered as simply as by calling render_table on the query object:

Code Output
query.render_table(self) do |t|
  t.override_heading :category_name, "Category"
  t.override_heading :created_at, "Date"

t.format(:created_at) { |val| val.strftime("%Y-%b-%d") rescue "" } t.format(:amount) { |val| number_to_currency(val) } end

There are a number of options available to use when defining your table:

Option Description
display_nil_as(value) Show value for any cell that would contain nil
number_format(format) How to format numeric data by default
format(col, &block) Format the specified column by passing each val to the given block
override_heading(col, heading) Use heading as the column header for the given column
Clone this wiki locally