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 ho
From console:
view = ApplicationController.view_context_class.new("#{Rails.root}/app/views")
JbuilderTemplate.encode(view){|json| json.partial!('path/to/index', @my_object) }
via https://github.com/rails/jbuilder/issues/84#issuecomment-38109709
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:
Have the client GET /users/index.json
or
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.
Looking at the source code, it looks like you can do:
json_string = Jbuilder.encode do |json|
json.partial! 'path/to/index', @my_object
end
in controller you can do like this
def index
json = JbuilderTemplate.new(view_context) do |json|
json.partial! 'index'
end.attributes!
do_something(json)
render json: json
end
note that you need "_index.json.jbuilder" because it calls partial renderer
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
Following justingordon's tip.
If you are using a React component, you can do the following.
In your controller:
@users = User.all
In your view:
<%= react_component("YourComponentName",
props: render('your_template.json.jbuilder')) %>
This was tested on Rails 5.1.