17

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]}.
Kyle Decot
  • 20,715
  • 39
  • 142
  • 263

4 Answers4

25

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'
mechanicalfish
  • 12,696
  • 3
  • 46
  • 41
  • I tried `render partial: 'students/student.html.haml'` but got `Missing partial students/stundent.html.haml with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee, :haml]}.` – Kyle Decot Sep 30 '13 at 19:34
  • stundent? seems like a typo. If you copied from my answer, I had the same typo there. – mechanicalfish Sep 30 '13 at 19:37
7

You need to specify the partial format:

json.array! @students do |student|
  json.html render(student, formats: [:html])
end
Dorian
  • 7,749
  • 4
  • 38
  • 57
uberllama
  • 18,752
  • 2
  • 16
  • 8
1

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>
coisnepe
  • 480
  • 8
  • 18
0

Rails partials use an underscore in the filename but not in the code when referenced as a string (depending on how you are loading them of course). Usually a partial called posts/_post.html.haml will be referenced in code as render :partial => 'posts/post'

chris
  • 6,653
  • 6
  • 41
  • 54
  • the path the partial points to usually refers to a relative path from the app/views folder. – chris Dec 11 '13 at 16:19