Question

In my rails app I am using RABL and on the front end I'm using jquery datatables to view lists of data (actually using angular with a datatable directive).

I'm trying to implement server side pagination which calls for a slightly different return tree

There's a good thread on a solution to dealing with this within the RABL itself, but I'd rather have a function in my controller that wrapped the RABL result with the extra params.

For example in my controller I would rather have a

respond_with_datatable(@books)

whereas this method somehow calls the respond_with(@books) method and just returns the json array of foo's and within this method I can set up the appropriate response:

{
"sEcho": 1,
"iTotalRecords": 53,
"iTotalDisplayRecords": 10,
"aaData": [book_array]
}

I don't believe there is a method I can call which simply does what respond_with(object) does and just captures the json without responding. The benefit of using a method in the controller is that I don't need to change the RABL and I have some cases where I want to return the extra datatables format and other cases where I don't. Having the control in the controller is ideal. Any help is appreciated!

Was it helpful?

Solution

You can use render_to_string to render your RABL template into a string, and then deal with it from there. For instance you could parse it back to JSON and then manipulate it or embed it in a bigger JSON structure. Then you can use render to respond directly with your new data.

I just tested this in my app

def index
  @galleries = Gallery.all # or whatever
  respond_with_datatable
end

def respond_with_datatable
  template_json = JSON(render_to_string)
  json = {:new_data => "some new stuff", :orig_data => template_json}
  render :json => json
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top