Add it to your Gemfile:
gem 'data_table', :github => "coupa/data_table"
Then run bundle install
to install it.
Define a new data table for your controllers with the data_table
macro:
class ItemsController < ApplicationController
data_table :items, :scope => :active do
column :name
column :price, :label => "$"
end
end
Then in your views, you can render the data table using the render_*_table
helper method:
%h1 Items
= render_items_table
Columns are defined inside the block passed to data_table
using column
.
data_table :items do
column :id
column :name
column :price, :label => "$"
end
Minimally, column
takes a single argument which is the name of an attribute or association on the model. Columns will appear in your table in the order you define them in the block.
You can specify a custom label for each column by passing the :label
option. If you do not specify a label, DataTable will infer the label from the attribute name.
column
can also take a block which will be used to render the contents of the cell. This is most often used if you want to apply some formatting to the text inside:
data_table :items do
column :id
column :name do |record|
h.link_to record.name, item_path(record)
end
end
The block will receive one argument which is the model instance for the current row. Inside the block, you have access to the view helpers through the shortcut method h
.
N.b. while usually used for attributes on the model, column can render anything that is available as a public method on the model. This means that if you want to render some computed value, you can simply pass the name of a method on the model that computes that value.
Columns can be hidden by default by setting :display
to false
. They will still be available for searching and for custom views.
data_table :items do
column :id
column :name do |record|
h.link_to record.name, item_path(record)
end
column :category, :display => false
end
Options for the table itself are passed in a hash argument to data_table
.
The most common of these is the scope
option, which limits the scope DataTable uses to find records.
data_table :items, :scope => :active do
column :id
column :name
column :price do |r|
"$ #{r.price}"
end
end
You can also pass a lambda to evaluate a scope at runtime:
data_table :items, :scope => -> { Item.active.where(:created_by => current_user) } do
column :id
column :name
column :price do |r|
"$ #{r.price}"
end
end
You can create more default views using the views
option. This option takes hash of hashes representing view options.
VIEWS = {
:under_25 => {
:name => "Under $25",
:scope => -> { Item.active.where("price <= ?", 25) }
}
}
data_table :items, :views => VIEWS do
column :id
column :name
column :price do |r|
"$ #{r.price}"
end
end
The keys to the views hash are internal identifiers that DataTable will use in the select box to identify your views. The name
option is the name that will be shown to users. The scope
option behaves the same as the table option.