I have a js.erb file with the following code but I can’t seem to properly escape the javascript for the link_to helper method. I think it has something to do with the quotation marks around Edit.
$('#microposts').prepend('<div class="micropost"><h3>' + "<%= j @user.email %>" + '</h3> <h3>Posted ' + "<%= j time_ago_in_words(@micropost.created_at) %>" + ' ago</h3><p>' + "<%= j @micropost.content %>" + '</p><p>' + "<%= j link_to "Edit", edit_user_micropost_path(@micropost) %>" '</p></div>');
$('#new_micropost')[0].reset();
$('#micropost_count').html('<%= Micropost.count %>');
On a side note, how would I animate this?
It’s possible this isn’t exactly the answer you’re looking for, but I would humbly suggest that this isn’t the right approach and the difficulty of escaping this properly is just a symptom of the approach being too complex.
I know what you’re doing here might actually be par for the course (according to some Rails developers), but I see this as a inefficient, and worse, too complex (and therefore difficult to maintain). Presumably some AJAX call has been made and received this dynamically generated response containing an imperative (commands to DO something; in this case, commands to modify the DOM) implemented in JavaScript. Why not have one static chunk of JavaScript loaded when the page initially loads that knows how to take a small snippet of DATA and render it appropriately?
What you’d then do is return JSON instead of an imperative chunk of script. Your static JavaScript method would modify the DOM by:
Think this would be more straightforward with much easier maintenance.