# SmartTable Implements tables with pagination and search for Rails, with server-side content loading. ## Installation Add this line to your application's Gemfile: ```ruby gem 'smart_table' ``` And then execute: ``` bundle ``` ## Getting Started ### Including Assets SmartTable uses both JS and CSS, that must be included in your app's asset pipeline. ``` // Add this to your application.js or vendor.js //= require smart_table // Add this to your application.scss or vendor.scss *= require smart_table ``` ### Setting up the Controller Add this line to your index action: ```ruby def index smart_table_params = smart_table_params(initial_page_size: 20) ... end ``` You can now use the `smart_table_params` object to customize your record's loading and counting: ```ruby # smart_table_params.search => string typed by user on search box (might be nil or empty) # smart_table_params.sort => string in the format of 'attribute ASC' or 'attribute DESC' (might be nil if there is no sorting specified) # smart_table_params.limit => page size (nil if showing all records) # smart_table_params.offset => record offset based on page number (nil if showing all records) @current_page_records = Record. where('column1 LIKE ? OR column2 LIKE ?', *Array.new(2, "%#{ActiveRecord::Base.sanitize_sql_like(smart_table_params.search)}%")). order(smart_table_params.sort). limit(smart_table_params.limit). offset(smart_table_params.offset) # Besides loading the records of the current page, the smart_table gem requires you # to count the total number of records of the table, so it can build the pagination # controls properly. Any filtering applied to record loading must be applied to # counting as well. @total_records_count = Record. where('column1 LIKE ? OR column2 LIKE ?', *Array.new(2, "%#{ActiveRecord::Base.sanitize_sql_like(smart_table_params.search)}%")). count ``` You can also use the `smart_table_params` to load/count records from another source, like an API or a NoSQL database. It is all up to you! ### Setting up the View Now in your view, use the following helpers to enhance your table: ```html
<%= smart_table_sortable("Username", :username) %> | <%= smart_table_sortable("Email", :email) %> | <%= smart_table_sortable("Name", :name) %> | <%= User.human_attribute_name(:account_type) %> | <%# this column is not sortable %>|
---|---|---|---|---|
<%= link_to "show", user_path(user) %> | <%= user.username %> | <%= user.email %> | <%= user.name %> | <%= user.account_type %> |