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.
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
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"
render partial: '/comments/comment', locals: {comment: comment}, layout: false
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With