Если вы делаете это в контроллере, гораздо проще вариант, чтобы попытаться двигаться код в поле зрения, оказываемые контроллером ,
Я описал это здесь: https://github.com/shakacode/react-webpack-rails-tutorial#jbuilder-notes
В принципе вы можете позвонить render
в представлении, и вы сделали. Как это:
<%= react_component('App', render(template: "/comments/index.json.jbuilder"),
generator_function: true, prerender: true) %>
Вот заметки о том, что произойдет, если вы хотите, чтобы передать данные из контроллера в представлении:
class PagesController < ApplicationController
def index
@comments = Comment.all
# NOTE: The below notes apply if you want to set the value of the props in the controller, as
# compared to he view. However, it's more convenient to use Jbuilder from the view. See
# app/views/pages/index.html.erb:20
#
# <%= react_component('App', render(template: "/comments/index.json.jbuilder"),
# generator_function: true, prerender: true) %>
#
#
# NOTE: this could be an alternate syntax if you wanted to pass comments as a variable to a partial
# @comments_json_sting = render_to_string(partial: "/comments/comments.json.jbuilder",
# locals: { comments: Comment.all }, format: :json)
# NOTE: @comments is used by the render_to_string call
# @comments_json_string = render_to_string("/comments/index.json.jbuilder")
# NOTE: It's CRITICAL to call respond_to after calling render_to_string, or else Rails will
# not render the HTML version of the index page properly. (not a problem if you do this in the view)
# respond_to do |format|
# format.html
# end
end
end
Вы пытаетесь вернуть JSON с контроллера как ответ JSON или буквально построить строку JSON в изоляции? – Winfield