Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render html partial in JSON JBuilder

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]}.
like image 443
Kyle Decot Avatar asked Sep 30 '13 19:09

Kyle Decot


3 Answers

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'
like image 92
mechanicalfish Avatar answered Nov 20 '22 18:11

mechanicalfish


You need to specify the partial format:

json.array! @students do |student|
  json.html render(student, formats: [:html])
end
like image 34
uberllama Avatar answered Nov 20 '22 19:11

uberllama


Here's what worked for me:

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

# students/_student.html.erb
<h4><%= student.name %></h4>
like image 1
coisnepe Avatar answered Nov 20 '22 17:11

coisnepe