简体   繁体   中英

Ruby on Rails implement Ajax Post and Comments

Someone could help me? Im trying implement the AJAX to my project and what i need to do should be very easy but for me becomed a madness days rsrs. My ideia is when the user add new comment shoud appear without reload page, below follow my controller, views and routes. Ahh to delete i did something that worked.

here is /app/controller/comments_controller.rb

在此输入图像描述

Post app/controller/posts_controller.rb

在此输入图像描述

Views Comments /app/views/comments/_template.html.slim

在此输入图像描述

Views Comments /app/views/comments/_form.html.slim

在此输入图像描述

Views Pots /app/views/posts/show.html.slim

在此输入图像描述

Solution to dele comment used

在此输入图像描述

create.js.erb

$("#comments").html("<%= escape_javascript(render partial: "comments/template", collection: @post.comments, as: :comment) %>");

_template.html.erb
<p class="comment-name"><%= link_to comment.user.name, user_path(comment.user_id)%>
  <span class="comment-content"><%= comment.content %></span> 
</p>
<p class="comment-time"><%= time_ago_in_words(comment.created_at) %></p>

CommentsController

def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.build(comment_params)
    @comment.save
    respond_to do |format|
      format.html { redirect_to :back }
      format.js 
    end 
end   

This might be too simplistic but maybe it will spark something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM