code_junkie

How do I expose data in a JSON format through a web service using Rails?

Nov 10th, 2011
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.55 KB | None | 0 0
  1. class Contact < ActiveRecord::Base
  2. ...
  3. end
  4.  
  5. map.resources :contacts
  6.  
  7. class ContactsController < ApplicationController
  8. ...
  9. def show
  10. @contact = Contact.find(params[:id]
  11.  
  12. respond_to do |format|
  13. format.html
  14. format.xml {render :xml => @contact}
  15. format.js {render :json => @contact.json}
  16. end
  17. end
  18. ...
  19. end
  20.  
  21. /contacts/1 # Responds with regular html page
  22.  
  23. /contacts/1.xml # Responds with xml output of Contact.find(1) and its attributes
  24.  
  25. /contacts/1.js # Responds with json output of Contact.find(1) and its attributes
Add Comment
Please, Sign In to add comment