Reputation: 23327
I'd like to use datatables in my rails application but I'd like to avoid prepraring JSON data by myself, so I'm looking for a gem that does it. Ideally I'd pass an ActiveRecored Relation and the gem generated JSON that could be consumed by datatables, for example:
class ItemsController < ApplicationController
def index
# I fetch data I need (taking into account authorization, search etc.)
@items = Item.find_relevant_items
respond_to do |format|
# gem prepares JSON for datatables
format.json { ItemDatatable.new(@items) }
# ...
end
end
end
I'm aware that there are several gems availabe. However, they don't suit me: jquery-datatables-rails is just a wrapper for the JS and the others seem to be outdated or not maintained (ajax-datatables-rails, rails_datatables, simple_datatables).
Do you know about any gem that would serve data for datatables?
Upvotes: 0
Views: 826
Reputation: 1171
The best way I have found to using datatables in a rails app is this:
jquery-datatables-rails gem to get all the assets datatables needs
ajax-datatables-rails gem to get the the JSON datatables expects when using server side pagination and searching.
There are other gems that make it easier to generate the JSON datatables need If you don't want to go through the trouble of making a new class like in the RailsCast. You can find them here
Upvotes: 1
Reputation: 12837
RABL and JBuilder both spring to mind. They are json template handlers and awesomely simple to use and both are equally powerfull enabling complete customisation of your json output.
There are railscasts on them both
http://railscasts.com/episodes/320-jbuilder
http://railscasts.com/episodes/322-rabl
and the sites
https://github.com/rails/jbuilder
https://github.com/nesquena/rabl
Both are well maintained.
Otherwise the datatables-rails gem is really the best option for you
http://railscasts.com/episodes/340-datatables?view=asciicast
UPDATE 2
It's the gem you have already looked at
As per railscast the gem is defined in the Gemfile
group :assets do
gem 'jquery-datatables-rails', github: 'rweng/jquery-datatables-rails'
gem 'jquery-ui-rails'
end
I strongly urge you to watch that railscast (http://railscasts.com/episodes/340-datatables?view=asciicast) as there are other configurations needed.
Upvotes: 0
Reputation: 160551
Ruby's JSON module is built-in, just require 'json'
at the top of a Ruby script to make it available. See "How do I parse JSON with Ruby on Rails?" for more information.
Rails also includes JSON capability too. See "Understanding Ruby and Rails: Serializing Ruby objects with JSON" for info using JSON and Rails. Rails is a fast-moving platform so that might be a bit out of date, but it should get you started. "Lightning JSON in Rails" is a good read for things to pay attention to as you generate JSON.
"JSON implementation for Ruby" is a great reference for Ruby and JSON also.
Upvotes: 2