Question

Is there an easy way to return data to web service clients in JSON using Rails?

Was it helpful?

Solution

Rails resource gives a RESTful interface for your model. Let's see.

Model

class Contact < ActiveRecord::Base
  ...
end

Routes

map.resources :contacts

Controller

class ContactsController < ApplicationController
  ...
  def show
    @contact = Contact.find(params[:id]

    respond_to do |format|
      format.html 
      format.xml {render :xml => @contact}
      format.js  {render :json => @contact.json}
    end
  end
  ...
end

So this gives you an API interfaces without the need to define special methods to get the type of respond required

Eg.

/contacts/1 # Responds with regular html page

/contacts/1.xml # Responds with xml output of Contact.find(1) and its attributes

/contacts/1.js # Responds with json output of Contact.find(1) and its attributes

OTHER TIPS

Rails monkeypatches most things you'd care about to have a #to_json method.

Off the top of my head, you can do it for hashes, arrays, and ActiveRecord objects, which should cover about 95% of the use cases you might want. If you have your own custom objects, it's trivial to write your own to_json method for them, which can just jam data into a hash and then return the jsonized hash.

There is a plugin that does just this, http://blog.labnotes.org/2007/12/11/json_request-handling-json-request-in-rails-20/

And from what I understand this functionality is already in Rails. But go see that blog post, there are code examples and explanations.

ActiveRecord also provides methods to interact with JSON. To create JSON out of an AR object, just call object.to_json. TO create an AR object out of JSON you should be able to create a new AR object and then call object.from_json.. as far as I understood, but this did not work for me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top