views:

1984

answers:

3

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

+1  A: 

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

format.json render :partial => "users/show.json"

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

Alex Reisner
+2  A: 

Try adding a view users/show.json.erb This should be rendered when you make a request for the JSON format, and you get the added benefit of it being rendered by erb too, so your file could look something like this

{
    'first_name': '<%= @user.first_name.to_json %>',
    'last_name': '<%= @user.last_name.to_json %>'
}
erik
You might want to use `@user.first_name.to_json` instead of `escape_javascript`. There are some subtle differences between what JS allows and what is *strictly* JSON. (And those differences are becoming important as browsers implement their own JSON parsers.)
James A. Rosen
Thanks for the suggestion; I updated the answer.
erik
A: 

Just add show.json.erb file with the contents

<%= @user.to_json %>

Sometimes it is useful when you need some extra helper methods that are not available in controller, i.e. image_path(@user.avatar) or something to generate additional properties in JSON:

<%= @user.attributes.merge(:avatar => image_path(@user.avatar)).to_json %>
Priit