1

I have tried to use ajax and jquery to render partial on-click. Please see Is it possible to render partial onclick without link_to? for details

It works, the partial got rendered but it's not working correctly.

I've placed the link_to inside a loop but when the "New Comment" is clicked, it appear on the first post, when I clicked the "New Comment" on the second/third/fourth posts, all of the partials got render on the first post. What is going on?

Please see below my code.

Post/index.html.erb

<% @posts.each do |post| %>

   <%= post.title %>

   <%= post.content %>

   <%= link_to 'New Comment', new_comment_path, id: 'new_comment', remote: true %>

<% end %>

Comment/new.js.erb

$('#new_comment').hide().after('<%= j render("form") %>')

_form.erb

<%= form_for(@comment) do |f| %>

  <div>
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </div>

  <div>
    <%= f.submit %>
  </div>

<% end %>

1 Answer 1

1

You are using the same ID for all your elements (Posts and New Comment Buttons) so when you click New Comment button all of the partials got render on the first post. Because it is the first matching element found. You should use different element IDs for your posts so when clicking on New Comment you will know where (which post i mean)to render the form. for example you may use a counter like this:

<%= link_to 'New Comment', new_comment_path, id: 'new_comment_' + i++, remote: true %> then all you have to do is to pass the elements id and change the following line: $('#'+PassedElementId).hide().after('<%= j render("form") %>')

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the answer, it doesn't work, I got syntax error for <%= link_to 'New Comment', new_comment_path, id: 'new_comment_' + i++, remote: true %> , anyway each post has their own :id, do I need to pass the :id to jQuery so it knows what :id(post) it should render on?
@laman the problem is $('#new_comment').hide().after('<%= j render("form") %>'). all your comment buttons have the same id (new_comment) and when you try to hide the comment button and render comment form only the first row will be affected. you have to use unique ids for comment buttons. And by adding i++ i was just trying to introduce the strategy.
thanks for the reply, I don't really understand how $('#'+PassedElementId) works, I was wondering if you can explain it. Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.