Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Rails: Datatables JSON error

json rails jquery

  • Please log in to reply
No replies to this topic

#1 llywellyn

llywellyn

    Passenger

  • Members
  • 1 posts

Posted 09 October 2013 - 05:04 PM

I hope that I have posted this in the right forum - apologies if not.

I am trying to follow the Railscasts tutorial 340 to populate a JQuery Datatables component from server-side JSON data. The link to the tutorial is: http://railscasts.co.../340-datatables. I am customising the code to work with my own database table and data.  This involves using the jquery-datatables-rails gem which I have added to my gemfile and installed with bundler.

When I attempt to visit the link which should output the JSON to the datatable, I get the following error:

not opened for reading

 

The code in the controller which handles the request is as follows:

class DatadescriptionController < ApplicationController
layout "datadescription"

def index
respond_to do |format|
format.html
format.json { render json: DatasetIndexDatatable.new(view_context) }
end
end
end

and the DatasetIndexDatatable class which is instantiated in the format.json command looks like this:

class DatasetIndexDatatable
delegate :params, :h, :link_to, :number_to_currency, to: :@view

def initialize(view)
@view = view
end

def as_json(options = {})
{
sEcho: params[:sEcho].to_i,
iTotalRecords: Datadescription.count,
iTotalDisplayRecords: datasets.total_entries,
aaData: data
}
end

private

def data
datasets.map do |dataset|
[
id,
database,
table,
created_by,
name
]
end
end

def datasets
@datasets ||= fetch_datasets
end

def fetch_datasets
datasets = Datadescription.order("#{sort_column} #{sort_direction}")
datasets = datasets.page(page).per_page(per_page)
if params[:sSearch].present?
datasets = datasets.where("name like :search or created_by like :search", search: "%# {params[:sSearch]}%")
end
datasets
end

def page
params[:iDisplayStart].to_i/per_page + 1
end

def per_page
params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
end

def sort_column
columns = %w[id database table created_by name]
columns[params[:iSortCol_0].to_i]
end

def sort_direction
params[:sSortDir_0] == "desc" ? "desc" : "asc"
end

end

Can anyone shed any light on what this 'not opened for reading' error means and how I can correct my code to output the json as intended?







Also tagged with one or more of these keywords: json, rails, jquery

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users