Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I render to a string a JSON representation of a JBuilder view?

Tags:

I'm using JBuilder as to return some JSON. I have a index.json.jbuilder that generates the data, and I need to render it to a string. However, I'm not sure how to do this, since: @my_object.to_json and @my_object.as_json don't seem to go through JBuilder.

How could I render the JBuilder view as a string?

like image 306
Geo Avatar asked Apr 13 '12 08:04

Geo


2 Answers

I am rendering a collection of users as a json string in the controller like so:

#controllers/users_controller.rb def index   @users = User.all   @users_json = render_to_string( template: 'users.json.jbuilder', locals: { users: @users}) end  #views/users/users.json.jbuilder json.array!(users) do |json, user|   json.(user, :id, :name) end 
like image 97
Aaron Renoir Avatar answered Sep 27 '22 21:09

Aaron Renoir


If the view users.json.jbuilder is at the default path relative to the controller and it cannot find the template, it may be due to a format discrepancy, as it may be trying to look for the html format file. There are two ways to fix this:

  1. Have the client GET /users/index.json

    or

  2. Specify the formats option when calling render_to_string (also applies to render):


#controllers/users_controller.rb def index   @users = User.all   @users_json = render_to_string( formats: 'json' ) # Yes formats is plural end 

This has been verified in Rails 4.1.

like image 28
Matt Avatar answered Sep 27 '22 20:09

Matt