In Rails, how do you render JSON using a view?

Matthew picture Matthew · Jan 18, 2010 · Viewed 150k times · Source

Suppose you're in your users controller and you want to get a json response for a show request, it'd be nice if you could create a file in your views/users/ dir, named show.json and after your users#show action is completed, it renders the file.

Currently you need to do something along the lines of:

def show
  @user = User.find( params[:id] )
  respond_to do |format|
    format.html
    format.json{
      render :json => @user.to_json
    }
  end
end

But it would be nice if you could just create a show.json file which automatically gets rendered like so:

def show
  @user = User.find( params[:id] )
  respond_to do |format|
    format.html
    format.json
  end
end

This would save me tons of grief, and would wash away that horribly dirty feeling I get when I render my json in the controller

Answer

Alex Reisner picture Alex Reisner · Jan 18, 2010

You should be able to do something like this in your respond_to block:

respond_to do |format|
    format.json 
    render :partial => "users/show.json"
end

which will render the template in app/views/users/_show.json.erb.