如何渲染部分字符串?

如何将部分字符串呈现为字符串,以便将其作为JSON响应的一部分包含在内? 我必须将它放入JSON响应中,以便为可能的错误消息留出空间。 以下代码给出了500服务器错误。 如果我只使用一个简单的render ,那么令人惊讶的是它有效。 好吧,它只发回纯HTML,无法解析为Javascript。

 respond_to do |format| format.html { redirect_to post_path(post) } format.js { { error: "", content: (render_to_string partial: '/comments/comment', locals: {comment: comment}, layout: false ) } } end 

错误

缺少模板缺少模板注释/创建,应用程序/创建{:locale => [:en],:formats => [:js,:html],:handlers => [:erb,:builder,:raw,: ruby,:jbuilder,:haml]}。 搜索:*“C:/ Users / Chloe / workspace / project / app / views”

工作,但发回纯HTML

 render partial: '/comments/comment', locals: {comment: comment}, layout: false 

好,我知道了。 我不得不添加render json: . 我以为我之前尝试过,它给了我一个双渲染错误。 我猜你在render_to_string ,可以有多个渲染。

 respond_to do |format| format.html { redirect_to post_path(post) } format.js { render json: { error: flash[:error], content: (render_to_string partial: '/comments/comment', locals: {comment: comment}, layout: false ) } } end