我在 Rails 4 中使用 JBuilder 渲染一些学生的 JSON。我希望每个学生都有一个"html"属性,其中包含给定学生的HTML部分:
[
{ html: "<b>I was rendered from a partial</b>" }
]
我尝试了以下方法:
json.array! @students do |student|
json.html render partial: 'students/_student', locals: { student: student }
end
但这给了我:
Missing partial students/_student with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee, :haml]}.
您必须指定部分格式,因为默认情况下,Rails 将使用当前格式 (json) 查找部分格式。例如:
render partial: 'students/student.html.erb'
您需要指定部分格式:
json.array! @students do |student|
json.html render(student, formats: [:html])
end
以下是对我有用的方法:
# 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>
Rails 部分在文件名中使用下划线,但在作为字符串引用时不使用代码(当然取决于您如何加载它们)。 通常,部分调用的posts/_post.html.haml将在代码中引用为渲染:p artial => 'posts/post'