I’m reading this Railscast: http://railscasts.com/episodes/340-datatables?view=asciicast
Mid-way down the page, Ryan says
The as_json method is triggered behind the scenes by the render_json
call in the controller.
but no more explanation is given. I’m trying to have this class respond with CSV as well, but def as_csv in the class and format.csv { render :csv => in the calling controller does nothing.
So, somehow the class knows when it was initialized by render :json, but I can’t figure out how to make it know it was initialized by render :csv. Can someone explain this?
If you pass an object to
render :json, theas_jsonmethod is called on that object to retrieve a JSON representation of that object. You can overwrite this method so that it returns whatever you want.This only works specifically for JSON, it’s not a general rule that can be applied to all formats. If you’d like to render a CSV representation of some object, you can do it easily enough by using something like:
and then implementing the
as_csvmethod in the class.