Render html partial in JSON JBuilder

Kyle Decot picture Kyle Decot · Sep 30, 2013 · Viewed 7.8k times · Source

I am rendering JSON of some students using JBuilder in Rails 4. I want each student to have a "html" attribute that contains the HTML partial for a given student:

[
  { html: "<b>I was rendered from a partial</b>" }
]

I have tried the following:

json.array! @students do |student|
  json.html render partial: 'students/_student', locals: { student: student }
end

But this gives me:

Missing partial students/_student with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee, :haml]}.

Answer

mechanicalfish picture mechanicalfish · Sep 30, 2013

You have to specify the partial format as Rails will look for partial with current format (json) by default. For example:

render partial: 'students/student.html.erb'