我怎样才能将字符串呈现为JBuilder视图的JSON表示?

Geo*_*Geo 22 json ruby-on-rails jbuilder

我正在使用JBuilder来返回一些JSON.我有一个index.json.jbuilder生成数据,我需要将其渲染为字符串.但是,我不知道如何做到这一点,因为:@my_object.to_json并且@my_object.as_json似乎没有通过JBuilder.

我怎么能将JBuilder视图渲染为字符串?

Aar*_*oir 43

我在控制器中将一组用户呈现为json字符串,如下所示:

#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
Run Code Online (Sandbox Code Playgroud)

  • 答案对我不起作用.render_to_string将响应的内容类型更改为json(索引应该呈现html) (3认同)

Mat*_*att 9

如果视图users.json.jbuilder位于相对于控制器的默认路径并且找不到模板,则可能是由于format存在差异,因为它可能正在尝试查找html格式文件.有两种方法可以解决这个问题:

  1. 请客户GET /users/index.json

    要么

  2. formats调用时指定选项render_to_string(也适用于render):


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

这已在Rails 4.1中得到验证.

  • 轨道4.1上的任何人都应该使用这个答案. (2认同)

jus*_*don 5

如果您在控制器中执行此操作,则更简单的选择是尝试将代码移动到控制器呈现的视图中。

我在这里描述了这个:https : //github.com/shakacode/react-webpack-rails-tutorial/blob/master/docs/jbuilder.md

基本上你可以render在视图中调用,你就完成了。像这样:

<%= react_component('App', render(template: "/comments/index.json.jbuilder"),
    generator_function: true, prerender: true) %>
Run Code Online (Sandbox Code Playgroud)

如果要将数据从控制器传递到视图,会发生什么情况,请注意以下事项:

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
Run Code Online (Sandbox Code Playgroud)