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

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


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.


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 %>"}


As others have mentioned you need a users/show.json view, but there are options to consider for the templating language...

ERB

Works out of the box. Great for HTML, but you'll quickly find it's awful for JSON.

RABL

Good solution. Have to add a dependency and learn its DSL.

JSON Builder

Same deal as RABL: Good solution. Have to add a dependency and learn its DSL.

Plain Ruby

Ruby is awesome at generating JSON and there's nothing new to learn as you can call to_json on a Hash or an AR object. Simply register the .rb extension for templates (in an initializer):

ActionView::Template.register_template_handler(:rb, :source.to_proc)

Then create the view users/show.json.rb:

@user.to_json

For more info on this approach see http://railscasts.com/episodes/379-template-handlers