Scenario:A post has many comments. In the index page of posts, when user clicks the show link( link_to post), its comments will show below the post.
Here I use the append() to add the comments:
$('#edit_post_<%= @post.id %>').append('<%= j render "comments/comments" %>')So when user click the show link, comments would be load and show up.
But how can I hide these comments again (i.e to make comments toggeable) ?
posts/index
<h1>Posts</h1>
<% @posts.each do |post| %>
<%= form_for post, remote: true do |f| %>
<%= post.content %>
<div id="post_<%= post.id %>">
<%= link_to "show", post, remote: true %>
</div>
<% end %>
<% end %>
posts/show.js.erb
$('#edit_post_<%= @post.id %>').append('<%= j render "comments/comments" %>')
comments/_comments.html.erb
<% @comments.each do |comment| %>
<%= comment.content %>
<% end %>
I suppose you dont have the event bindings for new comments.
you should use something like
so toggling works for all (also future) elements.
EDIT:
given the changes in the question: if toggle means just hiding the whole comment list,
you have to do it manually.
i suggest you have separate show / hide buttons (you can show and hide the buttons upon changing state as well), because if not, it gets more complex.
so for example, in posts/index:
in comments/_comments.html.erb
and in posts/show.js.erb
and in assets/javascripts/posts.js (be sure you include this in your application.js)
backbone.js is a great tool, if you’ll be doing a lot of things with those comments, like CRUD etc. and you need to stay on one page – use backbone.js. if not, stick to jQuery.