Trouble inserting a rails partial using JQuery

Diego Ocampo picture Diego Ocampo · Jul 4, 2011 · Viewed 9k times · Source

The following line of code:

$("#comments_<%[email protected] %>").append("<%= escape_javascript(render :partial => 'posts/comment', :locals => { :comment => @comment }) %>");

Is supposed to instert a partial as html inside the coments_xx div tag. what is happening is that the content of the partial is inserted but not interpreted as html, i mean, instead of inserting a comment with its right format i see the whole code in the web page:

Example (this is how it insert it in the webpage):

1 Comment
<div id=comment_5_34> <span class=dateandoptions> Posted less than a minute ago<br/> 
<a href=/comments/34/5 data-method=post data-remote=true rel=nofollow>Deletea> span>
<p><b>otra pruebab> wrote:p> <br/> <p><b> Webpage:b>asss.comp> <br/> <p class=comment-body>heeyeyeyyhep>div>

Thanks for commenting!

If i analize the javascript code inserted i get something like this (i used firebug extension to see it):

/* Add the new comment to the bottom of the comments list */
$("#comments_5").append("&lt;div id=comment_5_34&gt;    &lt;span    class=dateandoptions&gt;        Posted less than a minute ago&lt;br/&gt;        &lt;a href=/comments/34/5 data-method=post data-remote=true rel=nofollow&gt;Deletea&gt;    span&gt;    &lt;p&gt;&lt;b&gt;otra pruebab&gt; wrote:p&gt;    &lt;br/&gt;     &lt;p&gt;&lt;b&gt; Webpage:b&gt;asss.comp&gt;     &lt;br/&gt;    &lt;p class=comment-body&gt;heeyeyeyyhep&gt;div&gt;"); 

Finally this is the code of the partial that i am inserting:

<div id="comment_<%=comment.post.id%>_<%=comment.id%>">
<span class="dateandoptions">
    Posted <%= time_ago_in_words(comment.created_at) %> ago<br/>
    <%= link_to 'Delete', {:controller => 'comments', :action => 'eliminar', :id => comment.id, :post_id => comment.post.id}, :method => :post, :remote => true %>
</span>
<p><b><%= comment.user_name %></b> wrote:</p>
<br/>
<% if comment.web_page != nil %> <p><b> Webpage:</b><%= comment.web_page %></p> <% end %>
<br/>
<%= content_tag(:p, comment.contenido, :class => "comment-body") %>
</div> 

Hope i could explain myself well!

thanks in advance for your help.

Answer

diegopau picture diegopau · Jul 5, 2011

I found the solution!! Just having the rails code inside #{ }:

$("#comments_<%[email protected] %>").append("<%= escape_javascript("#{render :partial => 'posts/comment', :locals => { :comment => @comment }}").html_safe %>");