Brian's Blog

items I see across my tribes

Rails to return JSON

January 30
by briancarter 30. January 2011 09:11

This was an easy thing to accomplish in RoR… almost too easy.  Update your controller’s action to:

  def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }
      format.json { render :json => @posts }
    end
  end

The last format line is all it takes.  Bring up the page with the json extension: http://localhost:3000/posts.json

[{"post":{"name":"Post1","created_at":"2011-01-29T22:54:03Z","title":"This is Post 1 title","updated_at":"2011-01-29T22:54:03Z","id":4,"content":"Post 1 content"}},{"post":{"name":"Post2","created_at":"2011-01-29T22:55:25Z","title":"This is Post 2","updated_at":"2011-01-29T22:55:25Z","id":5,"content":"This is content for post 2"}},{"post":{"name":"dfasdf","created_at":"2011-01-30T00:36:36Z","title":"dfasf","updated_at":"2011-01-30T00:36:36Z","id":8,"content":"dfsdfd"}}]

That’s it. 

Categories:


 Questions or Feedback, my contact information is located on my About page.


The opinions, thoughts, and comments made in these blog posts are solely my own (unless otherwise stated). They do not reflect the opinions, thoughts or practices of my employer, my universities, my family, or anyone else. Also, I retain the right to change my mind about anything I publish here without having to go back and edit posts that occurred in the past. 

These are my opinions, or just as likely, someone else's opinions that I leveraged for my own.