Search code examples
ruby-on-railsruby-on-rails-4dynamicform

Dynamically "attach" a form in Rails 4


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...)


Solution

  • 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