2016-05-14 155 views
1

有人可以幫助我嗎?我試圖實現AJAX到我的項目,我需要做的事情應該很容易,但對我來說,成爲一個瘋狂的日子rsrs。 我的理念是當用戶添加新評論時,出現 沒有重新加載頁面,下面按照我的控制器,視圖和路線。啊刪除我做了一些工作。Ruby on Rails實現Ajax Post和註釋

這裏是/app/controller/comments_controller.rb

enter image description here

郵政應用程序/控制器/ posts_controller.rb

enter image description here

查看評論/應用/視圖/評論/ _template .html.slim

enter image description here

查看評論/app/views/comments/_form.html.slim

enter image description here

查看花盆/app/views/posts/show.html.slim

enter image description here

解決方案刪除評論使用

enter image description here

+0

如何使用$ .ajax,將評論文本發送到您的控制器,驗證它,如果有效,則返回true。在收到真正的$(comment-持有者).append(新評論)..哦,你正在尋找$ .ajax語法? – venkatKA

+0

我真的想這樣的事情 jQuery的 - > #創建註釋 $ 。對 「AJAX:beforeSend」( 「註釋的形式。」),(EVT,XHR,設置) - > $(本) ('textarea') .addClass('uneditable-input') .attr('disabled','disabled'); .on「ajax:success」,(evt,data,status,xhr) - > $(this).find('textarea') .removeClass('uneditable-input') .removeAttr('disabled', 'disabled') .val(''); $(xhr.responseText).append($(「#comments_container」))。show('slow') – Edson

+0

請將您的代碼作爲文本而不是快照發布? –

回答

0
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 

這可能太簡單了,但也許會激發一些東西。

+0

爲了更加清楚,我使用gem'acts_as_commentable_with_threading',註釋控制器可以用於任何其他模型,並且您給我的解決方案將改變事物的運作方式。謝謝。 – Edson