views:

26

answers:

1

I am experimenting with Rails and was wondering what's needed to allow/add support for JSON requests?

I have a vanilla installation of Rails 2.3.5 and the default scaffolding seem to provide support for HTML & XML requests but not JSON.

class EventsController < ApplicationController
  # GET /events
  # GET /events.xml
  def index
    @events = Event.all

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

  # GET /events/1
  # GET /events/1.xml
  def show
    @event = Event.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @event }
    end
  end

...

I'm new to this but it would appear as though i would need to add a format line in each method along the lines of:

format.js  { render :js => @event.json }

couldn't this be done automatically? perhaps there's a template somewhere i need to update...or a flag i can set? Or perhaps, and most likely, I've missed the boat entirely?!?

+2  A: 

You do:

format.json {render :json=>@event}

That will render the default activerecord JSON for the model

The option of ease of use is that you can write a private method which takes the format object and an object to render and then, based on the format, renders different things. Example:

class MyController<ApplicationController
  def show
    @event=Event.find(params[:id])
    respond_to do {|format| myRenderer(format,@event)}
 end
  ...
  private
  def myRenderer(fmt,obj)
    fmt.json {render :json=>obj}
    fmt.html
    fmt.xml {render :xml=>obj}
 end
Maz
So that's it? just add that line and...presto!?! is there a way to get the framework to include the `.json` lines in every `respond_to` block when the scaffold is created? *still digesting the 2nd part of your comment about a custom myRenderer...*
Meltemi
You can add it to the default scaffold generator template. The second part of my answer is just an ease of use thing.
Maz