在我的rails应用程序中,我正在使用RABL,而在前端,我正在使用jquery数据表来查看数据列表(实际上是在datatable指令中使用angular)。
在RABL本身中解决此问题的解决方案上有一个不错的线程,但是我宁愿在控制器中使用一个函数,将RABL结果包装在额外的参数中。
例如,在我的控制器中,我宁愿有一个
respond_with_datatable(@books)
而此方法以某种方式调用response_with(@books)方法并仅返回foo的json数组,并且在此方法中,我可以设置适当的响应:
{
"sEcho": 1,
"iTotalRecords": 53,
"iTotalDisplayRecords": 10,
"aaData": [book_array]
}
我不相信有一个我可以调用的方法,它可以简单地完成response_with(object)的工作,并且只是捕获json而没有响应。在控制器中使用方法的好处是,我不需要更改RABL,并且在某些情况下我想返回额外的数据表格式,而在其他情况下则不需要。在控制器中具有控制是理想的。任何帮助表示赞赏!
您可以使用render_to_string
将RABL模板呈现为字符串,然后从那里处理它。例如,您可以将其解析回JSON,然后进行操作或将其嵌入更大的JSON结构中。然后,您可以使用render
直接用您的新数据进行响应。
我刚刚在我的应用中测试过
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句