Im using thinking sphinx and it has become necessary to pull out the search results as JSON array with callback (JSONP). In my other functions like show, adding .json?callback=asd to the url allows this. But not for what i have retrieved with thinking_sphinx. This is what my index looks like
def index
#profiles = Profile.search params[:search], :match_mode => :any
respond_to do |format|
format.html # show.html.erb
format.json { render :json => #profiles, :callback => params[:callback] }
end
end
Ive been able to say /profiles.json?search=what to get a json. But how do i get a callback
What kind of url do i need to send, or other change i need to make, to get the right format for my models -- wrapperFunction(arrayOfJSONs)
Just add the callback as another query parameter:
/profiles.json?search=<query>&callback=<callbackname>
Just substitute <query> and <callbackname> with your values.
Related
To start out I have already looked at this thread and this thread.
I have a piece of code that has a couple different postgres calls, and then appends on another model collection named Category within our response. I want to filter out certain pieces of response depending on a search param passed in by the json. My current code is here:
def clues
....
clues = clues.where("category_id = ?", params[:category]) if params[:category].present?
offset = params[:offset].present? ? params[:offset] : 0
#result = clues.limit(100).offset(offset)
respond_to do |format|
if(!params[:category_keyword])
format.json { render :json => #result.to_json(:include => :category) }
else
format.json { render :json => #result.to_json(:include => Category.where("title LIKE ?", '%' + params[:category_keyword] + '%')) }
end
end
end
Right now, the end if statement in the respond_to do is broken, as I don't think my :include for the else statement is in a correct format to filter out, as it just doesn't append the nested model to my json response. What is the best way to filter out these nested calls?
I'm aware of the other questions pertaining to this subject, but none seem to help. I want the paperclip image url passed to json so I can render it in a reactjs component. I obviously cannot use Rails' image_tag helper.
I've defined this method in my items model
def image_url
image.url(:thumb)
end
And this in my controller
def index
#items = Item.all
render :json => #items.to_json(:methods => [:image_url])
end
But literally all that does is replace the rendered page with json. How should I go about this? It doesn't make sense to create a migration and model validation specifically for the image url.
Just needed to format the html.
respond_to do |format|
format.html
format.json { render :json => #items.to_json(:methods => [:image_url]) }
end
Still doesn't solve the part where I'm trying to use that method in a reactjs component, but that's another issue.
I'm trying to create a JSONP API for my Rails 3 application. Right now in my controllers, I have a lot of actions which follow this pattern:
# This is from my users_controller.rb, as an example
def index
#users = User.all
respond_with(#users, :callback => params[:callback])
end
While this works as is, I would like to DRY it up by not having to repeat the :callback => params[:callback] in every action's call to respond_with. How can I do this?
Update: One thing I've realized that is ugly about my above code is that the :callback => params[:callback] option will be passed for any response format, not just JSON. The following code is probably more correct:
def index
#users = User.all
respond_with(#users) do |format|
format.json { render :json => #users, :callback => params[:callback]}
end
end
There are a couple ways I've considered to address this problem, but I can't figure out how to make them work:
Override render (perhaps in the application controller) so that it accepts a :jsonp option that automatically includes the :callback => params[:callback] parameter. This way I could change the above code to the following, which is somewhat shorter:
def index
#users = User.all
respond_with(#users) do |format|
format.json { render :jsonp => #users}
end
end
Create a responder that overrides to_json in order to solve my problem. That way I could leave out the block and just call respond_with(#users, :responder => 'MyResponder') to solve the issue. Or perhaps I could include this code in an application responder using plataformatec's responders gem so that respond_with(#users) by itself would be sufficient.
Note that technically, it is incorrect to render JSON with a callback parameter, since you get a JavaScript response (a function call to the JSON-P callback) rather than a JSON result.
So if you have
render :json => my_object, :callback => params[:callback]
and a request for /users?callback=func comes in, Rails would answer
func({…})
with content type application/json, which is incorrect, since the above response is clearly not JSON but JavaScript.
The solution I use is
def respond_with_json(item)
respond_with do |format|
format.json { render :json => item }
format.js { render :json => item, :callback => params[:callback] }
end
end
which responds correctly with or without callback. Applying this to the aforementioned solution, we get:
def custom_respond_with(*resources, &block)
options = resources.extract_options!
if params[:callback]
old_block = block
block = lambda do |format|
old_block.call(format) if block_given?
format.js { render :json => resources[0], :callback => params[:callback] }
end
end
respond_with(*(resources << options), &block)
end
Also note the correction to resources[0], otherwise you end up wrapping resources in an extra array as a result of the splat operator.
THere's a gem that can do this to: rack-jsonp-middleware.
The setup instructions are pretty scant on the site, but I did create a little Rails project that uses it - which you can take a look at the commits and see what I did to get the middleware up and running.
https://github.com/rwilcox/rack_jsonp_example
This is bit 'low-tech' compared to the reponder solution, but what about just creating a private method in your appliation_controller.rb to handle this. The params variable will be available to it and you could pass the #users object to it.
#application_controller.rb
private
def jsonp(my_object)
render :json => my_object, :callback => params[:callback]
end
#controller
def index
#users = User.all
respond_with(#users) do |format|
format.json { jsonp(#users)}
end
end
Thanks to samuelkadolph for helping me in the #rubyonrails IRC channel today. He provided a solution in this gist, copied below for convenience:
def custom_respond_with(*resources, &block)
options = resources.extract_options!
if options[:callback]
old_block = block
block = lambda do |format|
old_block.call(format) if block_given?
format.json { render :json => [] }
end
end
respond_with(*(resources << options), &block)
end
I haven't tried this in my application yet, but I can see that it should work. He also confirmed that I could similarly override the respond_with method itself simply by changing the name of this method and changing the last line of the definition to super(*(resources << options), &block).
I think this will work for me. However, I'm still interested in knowing how to write a custom responder to do the job. (It would be a more elegant solution, IMHO.)
Update: I tried this in my application and it works with some minor changes. Here is the version I'm using now in the private section of my ApplicationController, designed to automatically provide the :callback => params[:callback] option to JSON requests:
def custom_respond_with(*resources, &block)
options = resources.extract_options!
if params[:callback]
old_block = block
block = lambda do |format|
old_block.call(format) if block_given?
format.json { render :json => resources, :callback => params[:callback] }
end
end
respond_with(*(resources << options), &block)
end
Note that I had to change if options[:callback] to if params[:callback] in order to get it working.
You can also check out this answer. basically you can create a "default" respond_to for your controller so you can just make your all your actions default to responding to json.
was that what you were asking?
I'm trying to pass an object (the current user) to be used when rendering the json for a collection.
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #items }
format.json { render :json => #items.to_a.as_json(:user => current_user) }
end
However, this seems to have no effect as options[:user] is nil in the as_json method.
JSON_ATTRS = ['id', 'created_at', 'title', 'content']
def as_json(options={})
# options[:user] is nil!
attributes.slice(*JSON_ATTRS).merge(:viewed => viewed_by?(options[:user]))
end
Anyone know why this doesn't work, or can suggest a more elegant way to have the json renderer be aware of the current user?
Thanks,
Wei
you are calling as_json on an Array (#items.to_a), are you sure that is what you want?
If you are trying to call it on your models then you need to do something like #items.to_a.map{|i| i.to_json(:user => current_user)} (and you probably don't need the to_a).
And it is to_json you should be calling. It will invoke as_json to get your properties, passing along whatever options you provide it with, but return a properly formated json-string (as_json returns a ruby object).
BTW, if you want to pass the options on down to "child" associations, I found that this worked (at least on a mongo_mapper backed project):
def as_json(options={})
{
:field1 => self.field1,
:field2 => self.field2,
:details => self.details.map{|d| d.to_json(options)}
}
end
Until now I have always specified the format of the response for actions using a responds_to block, like so:
responds_to do |format|
format.js { render :json => #record }
end
Recently I realized that if you only support one format (as in the above example), you don't really need that block. Is it best practice to leave it in, or remove it?
I'm going to differ with existing answers--I like to have a responds_to block for all of my actions. I find that, while slightly more verbose, it more clearly self-documents the action. It also makes it easy to support additional formats in the future. Edit: another advantage is it acts as a gatekeeper. Any format not declared in the block is automatically served a "406 Not Acceptable"
I'm not really sure if this is best practice or not, but usually what I like to do is to leave the routes open to respond_to (i.e. by appending .:format to the end), but only use it in the controllers when it's necessary.
Example:
routes.rb
map.connect :controller/:action/:id.:format
model_controller.rb
# Return a collection of model objects
def action_with_multiple_responses
#models = Model.all
respond_to do |format|
format.html #=> action_with_multiple_responses.html
format.xml { render :xml => #models }
end
end
# Return the first model object
def action_with_one_response
#model = Model.first
end
That way, you aren't cluttering up your action_with_one_response method with an unnecessary block, but you also have set yourself up quite nicely if you want to someday return your object in xml, json, etc.
I would say not to use respond_to unless you have multiple response types.
It is simply extra code to understand and for your app to process and handle:
render :json => #record
Is much more concise than:
responds_to do |format|
format.js { render :json => #record }
end