Skip to content
AaronLasseigne edited this page Jan 26, 2012 · 9 revisions

table_for Columns

Inside the table_for call you can define the columns of data you want to display in the table. The order of the columns is the order they will appear in.

<%= table_for @records do |t| %>
  <% t.column(:first) %>
  <% t.column(:second) %>
  <% t.column(:third) %>
  <% t.actions do |record| %>
    <%= link_to('View', record_path(record)) %>
  <% end %>
<% end %>

column(name, options = {}, &block)

Adds a column to the table. A block can be sent to customize the data output to each cell. The block is passed the record currently being evaluated.

Options:

Any keys not listed below are used as standard HTML attributes on a col tag. For example, width: "200px" could be passed and would apply to a col tag for that column.

  • :cell_attrs - A hash of attributes to apply to the td tag. Values in the hash can be strings or procs. If a proc is passed to an attribute it is evaluated for each cell in the column. Procs are passed the current row of data evaluated.
  • :header - The name used to label the column. Defaults to a titlized version of the name.
  • :header_attrs - A hash of attributes to apply to the th tag.
  • :show_sort - When set to true turns sorting on for the column. Defaults to the value from :show_shorts on the table_for call.

Examples:

<% t.column(:first_name, header: 'Given Name', show_sort: true) %>

<% t.column(:created_at) do |record| %>
  <%= record.created_at.strftime('%m/%d/%Y') %>
<% end %>

<% t.column(:total, cell_attrs: {style: ->(row){"color: #{row.total >= 0 ? 'black' : 'red'};"}}) %>

actions(options = {}, &block)

Creates an untitled column for actions such as view, edit, delete, etc. The code in the provided block will be executed for each row. The block is passed the record currently being evaluated.

Options:

Takes all of the same options as the column call except for :show_sort.

Examples:

<% t.actions do |record| %>
  <%= link_to('View', record_path(record)) %>
<% end %>

Table Model Columns

The other location that can contain column information is the table model. In the table model, columns can be used to change the default sort order.

column(name, options = {})

The name must match the name of a column located in the table_for call.

Options:

  • :sort - A SQL string in the same format that an ORDER BY clause would accept.

Example:

class RecordReport < Tableficate::Base
  scope :record

  column(:full_name, sort: 'first_name ASC, last_name ASC')
end