Let's say I have a Post model which has many comments. In the Posts#index page where all posts are shown, I want to allow users to add their comments for specific posts (I know it doesn't make much sense, it's just as a general idea).

the "brute force" way would be to attach a form on each post element but this smells bad. I'm sure there are better options which I can't think of right now, so, appreciate the help.

Thanks, Roy

(P.S - a good example would be FB page in which a user can comment to each of the posts in the timeline and I guess it's not by having a form for each one...)

有帮助吗?

解决方案

You could append the form to the page using JS & Ajax, like this:

#config/routes.rb
resources :posts do 
    resources :comments
end

#app/assets/javascripts/application.js
$(document).on("click", "a.new_comment", function() {#
    id = $(this).attr("id");

    $.ajax({
        url: $(this).attr("href");
        success: function(data) {
             $("#" + id).append(data);
        }
    });
});

#app/views/posts/index.html.erb
<% @posts.each do |post| %>
    <%= post.title %>
    <%= link_to "Add Comment", new_post_comment_path(post.id), class: "new_comment", id: post.id %>
<% end %>

#app/controllers/comments_controller.rb
def new
    @comment = Comment.new

    respond_to do |format|
        format.html { render layout: !request.xhr? }
    end
end

其他提示

You can add a "add comment" button which will make a ajax call to a controller action that will in response will return the html for the comments form (as a string). and then attach that html to your post element.

$(".post-element").each(function(index, post_element) {
  post_element = $(post_element);
  post_element.find(".add-comment").on("click", function(e) {
    e.preventDefault();
    $.get("/path/to/generate/form/html", function(html_response) {
      post_element.append(html_response);
    });
  });
});

You can also use the "Rails way" and use remote link with a js response but I prefer it this way.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top