Custom Table
Provides powerful set of functionality for showing tables of data:
- Generated table and filter panel for any model
- Declare fields that should be displayed, filtered or sorted
- Customize visible fields for each user
- Exporting table to XLSX (helpers for CAXLSX, fast_excel and CSV)
Requires and works only with Ransack, Kaminari, Bootstrap CSS, Rails, simple_form and Turbo gems.
Setup
- Run
rails generate custom_table installto create User migration and Initializer - Generate base helpers
- Add CustomTable engine routes
- Add concern to controllers
- Add CSS import to your application.css:
@import 'custom_table/table.css'; - Add concern to User model
- Declare your first model
Declaring fields
The most important part of using this gem is to correctly declare fields available for showing in table.
This should be declared in helper named by this pattern:
{singular_model_name}_custom_table_fields
And shold return hash of field definitions:
e.g.
def vegetable_custom_table_fields
fields = {}
fields[:color] = { search: { q: :color_eq, type: :text }, appear: :default }
return fields
end
Use attribute name as key if possbile. Table will try to get most of options automatically from model if you pass regular attribute.
Fields declaration options
labeladds label to the field. Will try to find human attribute name by defaultsearchcontains search parameters. Skip this if search is not available for this fields- *
qransack's "q" search marcher which is used to search by the field. For range use array of two elements, e.g.[:created_at_gteq, :created_at_lteq] - *
typetype of search element to draw - *
sm_visibleset to true to make this field search always be visible in small screens (by default all fields collapsed) appearcontrols visibility of the field. Default value is hidden if not specially selected- *
defaultwill appear by default - *
alwayswill always appear - *
exportwill appear only in XLSX export link_to_showif true, this fields will have link to show page of itemsortcontrols sorting ability for the fields (disabled by default). Usetrueor{default_order: :asc|:desc}amountif true, applies number-specific formatting to cells (right align)helperhelper name (will be used instead default, see below)total_scopescope which will be applied to collection to count total for rows. By defalt it takes sum(:field)
Controller setup
Add CustomTableConcern to your controller to get easy index page solution.
This gem provides custom_table method for your controller which does Ransack search and Kaminari pagination for you:
def index
@q = @vegetables.ransack(params[:q])
@q.sorts = 'created_at desc' if @q.sorts.empty? # Sets default sorting for ransack
@vegetables = @q.result(distict: true)
@vegetables = @vegetables.page(params[:page]).per(params[:per] || 25)
end
Is equivalent to:
def index
@vegetables = custom_table(@vegetables)
end
Optional parameters are:
default_sorts-stringsorting order if user not selected it (default tocreated_at desc)default_query- default ransackqobject. Default is empty
Rendering tables
Invoke this in your index to display table:
custom_table_data collection: @vegetables
Options available are:
- Second parameter is variant (can be skipped if you dont use variants)
collectionis the only required option. Contains paged collection from your controllerparentparent resource for inherited routesskip_fieldsarray of field names as symbols. Removes specific fields from tableskip_actionsremoves all actionsskip_default_actionsremoves default actionsactionshelper name for custom actions. Table also looks for{singular_model_name}_custom_table_actionshelper presencetotalsobject of fields to show totals. Use symbols as keys and pass value or left nil to let table try to count total based on raw/field valuepaginateset to false to skip paginationlast_pageset to false to disable last page count request for performancequick_filterset to true to enable simple full-text client-side searchwith_selectallows to add checkboxes toggler. Pass helper name which has (item, position) as parameterstreeset to true if you have parent-child relation and you want to show records grouped by parent. Be sure to disable pagination as it will only group current page recordsgroup_byset to helper name to group records by result of it. Be sure to disable pagination as it will only group current page recordsexpandedexpand grouped or trees by defaultsortableset to true to allow to sort models. Model needs to havepositionattribute and useacts_as_listgem to be sorted. Gem usesstimulus-sortableJS package for sorting
Rendering search panel
Use this helper in order to show filter panel:
custom_table_filter search_model: Vegetable
Options:
search_modelmodel class to use with this filter. The only required parameter.hide_customizationhides customization buttonfieldsif you want to have pre-defined fields, not from model definition
Displaying custom fields
You can declare fields which your model doesn't have. In this case table can't render field value so you have to provide helpers for rendering the field. Table renderer will try to look for these helpers in prioritizing order:
#{singular_model_name}_#{field}_fieldto avoid naming collisions#{singular_model_name}_#{field}best choise for most projects#{singular_model_name}_#{field}_rawuse this to produce non-decorated raw data which can be used in tables
If helper is not accessible table will try to render item via following methods:
- Association via
to_smethod - Numeric attribute via
amounthelper which formats number - Raw text attributes
- Boolean attribute via
boolean_iconhelper. Uses bootstrap icons and can be overriden
If you use variant, following helper will have the priority over all options:
#{singular_model_name}_#{variant}_#{field}_field#{singular_model_name}_#{variant}_#{field}
Displaying custom actions
Customizing user columns
Add CustomTable as engine to your routes:
And custom_table attribute as text to your model
Search Settings button will show up automatically if you have at least one customizable field.
You can also use settings button separatelly. It uses Rails turbo and you need to declare turbo-modal Turbo Tag within your HTML body.
Variants
For each table you can declare additional variants (set of parameters to be saved to user customization).
Important to note that you need to explicitly set list of available variants. Declare the following helper function:
{singular_model_name}_custom_table_fields
Which returns the array of available variant.
Then just pass variant to filter and data helpers.
Table Stimulus helper
Batch Actions
You can set batch option to field definition to enable batch editing
You need to set following options to custom_table_data:
batch_actions- shows batch actions. Set to helper name for custom actionsbatch_activator- shows more compact batch selecting view. Enabled by default
You have to declare the following routes for the resource:
batch_edit- POST withplural model namearray will be requested to show form for mass editingbatch_update- POST withplural model namearray will be requested to update records with paramsbatch_destroy- DELETE withplural model namearray will be requested to delete records
Downloading data as XLSX table
This gem also provide partial for exporting all available columns as XLSX file via CAXLSX gem:
wb = xlsx_package.workbook
wb.add_worksheet(name: "Aircrafts") do |sheet|
render 'custom_table/table', sheet: sheet, collection: @aircrafts.except(:limit, :offset)
end
Using fieldset helper for show actions
You can use the same fields declared for table within show views. This also can be used without any table fields declaration and setup.
The simpliest case here is (haml):
= fieldset @instance do |fs|
= fs.field :name
It will produce bootstrap fieldset formatting as well as value logic from tables.
Fieldset formatting can be overriden via views (custom_table/_fieldset and custom_table/field)
By default fieldset is integrated with turbo_editable gem and each field is wrapped with it. You can disable it by passing editable: false as param to fieldset of field.
Options available are:
label- if it cannot be received via field definitioneditable_params- hash of params to be passed to editable
All options from fieldset are proxied to field. So you can declare it once if suitable.
You can declare how each field is displayed. Just add it as block within field:
= fieldset @instance do |fs|
= fs.field :name do
= @instance.name.upcase
Testing hints for your app
Use custom_table_use_all_fields GET param with any value to show all available fields in your feature tests
Development
Running tests:
bundle installbundle exec rails db:migrateRAILS_ENV=test bundle exec rspec