So apparently in plain Rails, the render
syntax already handles the callbacks. Simply pass in callback: params[:jsoncallback] as an option would do the trick.
Click here and browse under the Rendering JSON section for the documentation.
Question
If not, how can I make it so that it is JSONP-compliant with my AJAX requests?
EDIT: It looks like I am not clear with what I want to achieve. Let's say for example that I have a Post class that contains attributes like id, author, tags and content. Now the following ActiveModel::Serializer is what I would use to code JSON response:
class PostSerializer < ActiveModel::Serializer
attributes :id, :author, :tags, :content,
end
Now in the controller, I would have do something like
render :json => @post
to generate a JSON file that looks like this
{
"posts": [
{
"id": 1,
"author": "John Doe",
"tags": "test",
"content": "Hello world"
}
]
}
Now my objective here is to use JSONP, so that when someone passes in a jsoncallback parameter in the request (e.g. GET '/posts?jsoncallback=callback_function'), I would be able to generate the following:
callback_function({
"posts": [
{
"id": 1,
"author": "John Doe",
"tags": "test",
"content": "Hello world"
}
]
})
Currently I am using to_json on a Post object and storing the result into a variable called @posts_json, then specifying the Content-Type as text/javascript in the controller, and rendering out an html.erb file that looks like the following:
<% if params[:jsoncallback].blank? %>
<%= @posts_json.html_safe %>
<% else %>
<%= params[:jsoncallback] %>(<%= @posts_json.html_safe %>)
<% end %>
I'm sure you'll agree that this solution is really ugly, and the issue is that it is starting to give me problems due to the to_json method that I am using in the controller.
As such, I would like to use ActiveModel::Serializer to obtain the same functionality. How might I do that?
Solution
So apparently in plain Rails, the render
syntax already handles the callbacks. Simply pass in callback: params[:jsoncallback] as an option would do the trick.
Click here and browse under the Rendering JSON section for the documentation.