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

后端 未结 8 1513
抹茶落季
抹茶落季 2020-12-29 05:18

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

8条回答
  •  一生所求
    2020-12-29 05:52

    You can also do it like this, which leaves your controller a bit cleaner.

    # controller
    def new
      @data = Data.all
    end
    
    
    # view
    <% content_for :head do %>
      
    <% end %>
    
    
    # path/to/_partial.html.jbuilder
    json.array!(@data) do |d|
      json.extract! field1, :field2, :field3, :field4
      json.url data_url(d, format: :json)
    end
    
    
    # layouts/application.html
    
    
    
      <%= yield :head %>
    
    
    ...
    
    
    

提交回复
热议问题