Giter Site home page Giter Site logo

simple_datatables's Introduction

Simple Datatables

Connects two awesome plugins - Datatables for Jquery and Meta Search together for Rails 3

Install

Add the following to your Gemfile to install simple datatables:

gem 'simple_datatables'

After bundle install add this line to rails assets pipeline and restart server:

//= require simple_datatables

Installation completed.

Description

There are two ways to map awesome Datatables plugin request fields for Rails.

  • First is to convert request on the server side

  • Second is to prepare correct request on the client side

This gem provides interface for the second way. To use it you should do the following easy three steps:

Create simple meta_search and will_paginate (optionally) controller action as usual and add “.datatables” format

respond_to :html, :datatables

def search
  @products = Product.search(params[:search]).paginate(:page => params[:page], :per_page=>params[:per_page])
  respond_with @products
end

Use standard datatables initializer options for creating table:

  • bServerSide: true

  • sAjaxSource: path to your controller

  • fnServerData: point to simpleDatatables function

  • aoColumns: you should define all searchable/fiterable sName attributes here. Use format as used in meta_search (with underscores)

Create Jsonify view with column values for columns listed in aoColumns. View should be written in Jsonify style and should have *.jsonify file extension in order to work properly. See example and Jsonify docs for more details.

Dependencies

This gem uses:

  • meta_search for nice search and sort request syntax mapping

  • jsonify for simple output generation

This gem provides integration with:

  • will_paginate for nice pagination request syntax mapping (not bundled)

Gem works only with rails 3.1 and higher.

Gem includes datatables library and fnSetFilteringDelay plugin so you haven’t include it by yourself.

Gem does not include any CSS files. Please use styles from datatables website examples.

Pagination

Simple_datatables is compatible with will_paginate. In order to provide choise freedom you should add will_paginate to your project by yourself. Datatables will provide you “page” and “per_page” request params.

If you do not use pagination do not forget to save search result to some variable with meta_search relation method:

@products = Product.search(params[:search]).relation

Your can use any other paginator. See below for the details.

Search for all fields

Note that fulltext search will work only with text fields due to meta_search restrictions. To prevent errors use bSearchable: false for non-text columns in aoColumns field.

Regex search

Due to meta_search restrictions it is impossible to use regex search for now.

Instead, this gem recognizes bSearch flag as “contains” meta_search finder.

By default “starts_with” is used due to database performance reasons.

Independent fields search will always search using “starts_with” finder.

Custom pagination implementations

If you are getting strange results (for instance, iTotalRecords and iTotalDisplayRecords both equal 0, or entirely the wrong collection is used), you might want to specify which collection to use:

@collection = @products
respond_with @products

Also if you are using own or uncommon implementation of pagination you may use direct page count variables setting as follows:

@total_entries = 12
@current_page_entries = 10
respond_with @products

In this case gem will not try to find collection or pagination and will use the counters passed via variables.

Example

The following code will show products list datatables. Manufacturer is belongs_to association for Product.

First of all add to your routes.rb datatables search api method:

resources :products do
  collection do
    get :search
  end
end

Then implement it in your controller:

respond_to :html, :datatables

# GET /products/search
def search
  @products = Product.search(params[:search]).paginate(:page => params[:page], :per_page=>params[:per_page])
  respond_with @products
end

In your search view (app/views/products/search.jsonify) implement output fields order:

@products.each do |product|
  json << [product.name, product.manufacturer.name]
end

In your index view make a table with header (HAML):

%table#products
  %thead
    %tr
      %th= Product.human_attribute_name :name
      %th= Product.human_attribute_name :manufacturer

  %tbody

In your javascript add the following code to initialize the datatables (be sure to do it after document load):

$("#products").dataTable({
    "sAjaxSource"     : "/products/search.datatables",
    "aaSorting"       : [[0, 'asc']],
    "aoColumns"       : [
      {"sName":"name"},
      {"sName":"manufacturer_name"},
    ],
    "bServerSide"     : true,
    "fnServerData"    : simpleDatatables
  });

Copyright © Grigory Dmitrenko, 2012. See LICENSE for details.

simple_datatables's People

Contributors

ehogberg avatar gryphon avatar meadmaker avatar pauldoerwald avatar seanbehan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

simple_datatables's Issues

Integration with themeroller

Trying to integrate with theme roller but the data rows in my datatable are not styled. Is there something missing from the data i am giving back? Is there some type of themeroller callback I am supposed to use?

Thx!

-karl

Parse error

I was trying to follow the instructions using the gem, but it gives me the next error:

http://localhost:3000/posts

Error: Parse error on line 69: Unexpected 'TERMINATOR'
(in F:/RailsInstaller/Ruby1.9.2/lib/ruby/gems/1.9.1/gems/simple_datatables-0.2.0/vendor/assets/javascripts/simple_datatables.js.coffee)

README clarifications

I'm trying to figure out how to use this, so I'm noting points in the README that are confusing me. Will gladly fork and pull-request once I figure things out.

  1. The example uses HAML notation, which I was unfamiliar with. Not that it's confusing, but I just had no idea what it actually was. I suggest either noting that it's HAML, or simply using regular erb syntax.

  2. Example refers to "your search view (app/views/products/search.jsonify)"... um, I don't have a search view, and I am unfamiliar with files that end in *.jsonify. Do I need to make a file that ends in *.jsonify? What does this kind of file look like?

    I suggest elaboration, or link to documentation about *jsonify files.

Custom pagination advice doesn't work

From the readme "Custom pagination implementations" section:

Also if you are using own or uncommon implementation of pagination you may use direct page count variables setting as follows:

respond_with @products, :locals => {:total_entries => 12, :current_page_entries => 10}

This does not appear to work. In application.datatables.jsonify, the variables total_entries and current_page_entries remain unset.

bRegex error

I encountered an error where the search text input was generating a string like
search[last_name_or_first_name_or_middle_namefalse]=L

i think it was trying to generate
search[last_name_or_first_name_or_middle_name_sw]=L

In the file simple_datatables.js.coffee, bRegex is initialized to false, and then line 71 says
op = bRegex ? "_contains" : "_sw"
which compiles to
op = bRegex != null ? bRegex : {
"_contains": "_sw"
};
so the next line
data.push({
name: "search[" + searchcolumns.join("or") + op + "]",
value: sSearch
});
appends "false".
The following change seems to fix the problem
// op = bRegex ? "_contains" : "_sw"
if (bRegex)
op = "_contains"
else
op = "_sw"

can include default css for datatables?

IMHO, we all need some css for datatables for all apps.
If default stylesheet was provided by default, it is very useful for everyone, as same as javascripts are included.
("so you haven’t include it by yourself." from README :-)

after data is retrieved the JS dies

This was my error.

Uncaught TypeError: Cannot read property 'length' of undefined
Aajquery.dataTables.min.js:69
i.fn.dataTable.a.iDrawjquery.dataTables.min.js:68
jQuery.Callbacks.firejquery-1.7.1.js:1047
jQuery.Callbacks.self.fireWithjquery-1.7.1.js:1165
donejquery-1.7.1.js:7400
jQuery.ajaxTransport.send.callbackjquery-1.7.1.js:8181

You really should not use the minified JS. I would have debugged the issue but I'm unsure if I am going down a hole to never return.

Parse error on line 69: Unexpected 'IDENTIFIER'

hi, i'm getting this error when i try to load any page after installing simple_datatables

Parse error on line 69: Unexpected 'IDENTIFIER'
(in /Users/jlinowes/.rvm/gems/ruby-1.9.2-p290/gems/simple_datatables-0.2.1/vendor/assets/javascripts/simple_datatables.js.coffee)

Extracted source (around line #8):

6: %meta{"http-equiv"=>"Content-Type", :content=>"text/html; charset=utf-8"}/
7: = stylesheet_link_tag "application"
8: = javascript_include_tag "application"
9: = csrf_meta_tag
10: = yield(:head)
11:

using rails 3.1.3

app/assets/javascripts/application.js contains

//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require rails.validations
//= require simple_datatables
//= require_tree .

Update to use latest datatables.js

Looks like this is using an older version of datatables (though I'm not sure which version).

Are there any plans to update it to the newest one?

support decent_exposure

hi, when i write my #search controller action as your examples, its ok

def search
    @people = Person.search(params[:search]).paginate(:page => params[:page], :per_page=>params[:per_page])
    respond_with @people, :locals => { :collection => @people }
end

But not when i use the decent_exposure gem,

expose(:people) { Person.search(params[:search]).paginate(:page => (params[:page] || 1), :per_page=>params[:per_page]) }
expose(:person)

def search
  respond_with people, :locals => {:collection => people}
end

Looking inside application.datatables.jsonify, the first way gets instance_variables

[:@_config, :@view_renderer, :@_routes, :@people, :@_assigns, :@_controller, :@_request, :@view_flow, :@output_buffer, :@virtual_path]

but with decent_exposure, the instance_variables are

[:@_config, :@view_renderer, :@_routes, :@_resources, :@_assigns, :@_controller, :@_request, :@view_flow, :@output_buffer, :@virtual_path]

But @_resources.class is a Hash, like { :people => [array of people] } not an active relation, and never equals collection.

simple_datatables

couldn't find file 'simple_datatables'

Looks like when i hit this line in my assets

//= require simple_datatables

I get an error.

$ rake assets:precompile

rake aborted!
couldn't find file 'simple_datatables'
(in /Users/d/p/ror_ecommerce/app/assets/stylesheets/admin.css.scss:3)

Tasks: TOP => assets:precompile:primary
(See full trace by running task with --trace)
rake aborted!
Command failed with status (1): [/Users/davidhenner/.rvm/rubies/ruby-1.9.2-...]

Tasks: TOP => assets:precompile

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.