Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I render a partial to a string?

How do I render a partial to a string, so I can include it as part of a JSON response? I have to put it into a JSON response to allow room for a possible error message. The following code gives a 500 server error. If I use just a plain render, then surprisingly it works. Well, it send back just plain HTML which cannot be parsed as Javascript.

Code

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

Error

Template is missing Missing template comments/create, application/create with {:locale=>[:en], :formats=>[:js, :html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :haml]}. Searched in: * "C:/Users/Chloe/workspace/project/app/views"

Works, but send back plain HTML

render partial: '/comments/comment', locals: {comment: comment}, layout: false
like image 725
Chloe Avatar asked Dec 22 '13 03:12

Chloe


1 Answers

Ok I got it. I had to add render json:. I thought I had tried that before and it gave me a double render error. I guess when you render_to_string, then it's ok to have more than one render.

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
like image 187
Chloe Avatar answered Oct 16 '22 15:10

Chloe