Reputation: 256
I'm building a reddit clone (just for practise)) and having a problem with a form for new comment reply. I used this tutorial for building polymorphic comments and everything works fine but I want to add forms for new comment replies just under the reply, so that you click a link and the form appears (the div with the form is hidden by default). But it seems that the form appears for each new object that I generate in my form, so It's just infinite cycle. Are there any ways for creating forms for comment replies?
Here's my _form:
= form_for comment do |f|
p
= f.label :body
= f.text_area :body
= f.hidden_field :link_id, value: params[:link_id]
- if params[:link_id]
= hidden_field_tag :link_id, params[:link_id]
- if params[:comment_id]
= hidden_field_tag :comment_id, params[:comment_id]
= f.submit "Create", class: "button tiny"
And the _comment partial:
li.comment
p = comment.body
p = link_to "Add a reply", "", class: "reply_link"
.comment_form
= render 'comments/form', comment: comment.comments.build
- unless comment.comments.empty?
ul.comments_list
= render partial: 'comments/comment', collection: comment.comments
Upvotes: 2
Views: 113
Reputation: 256
So, the solution was quite simple. Rather than rendering forms for each comment, which would be quite slow, I decided to user AJAX to build forms on the fly. Here's the _comment view:
- if comment.id && comment.user
li id="comment-#{comment.id}" class="comment"
h6 = "From #{link_to comment.user.email, user_path(comment.user)}".html_safe
.comment_body
= comment.body
= render 'shared/likes_panel', object: comment
= link_to "Reply",
new_comment_path(comment_id: comment.id),
remote: true
.comment_form
- unless comment.comments.empty?
= render 'comments/list', comments: comment.comments
As you can see, in link_to I use remote: true, which points to new action in the comments_controller which should respond to js:
def new
@comment = @parent.comments.new
@comment.user = current_user
respond_to do |format|
format.js
end
end
And finally you'll need new.js.erb to append the comment form to the right comment:
var li = $("#comment-<%= params[:comment_id] %>");
li.find(".comment_form").html("<%= j render 'comments/form' %>");
As soon as you comments in <ul>
, all the subcomments will be nicely indented!
Upvotes: 1
Reputation: 1920
I solved this issue with the following jQuery.
$(document).ready(function() {
$('.partner-area').click(function() {
$(this).next('.partner-offices').slideToggle(500);
});
});
Where above, .partner-area
is the class of the link to click on, and .partner-offices
is the class name of my form. This is basically saying that when whatever link is clicked, the very next form will animate and open.
Default css on the form display: hidden
Upvotes: 1