试图使用两个"远程真"在Rails中进行单独的Ajax调用

时间:2016-04-12 14:38:41

标签: jquery ruby-on-rails ajax

我试图允许用户使用Ajax调用在同一页面上发表评论并删除评论。目前,用户可以发表评论并删除评论但是当我在两个视图中输入远程true时,既不会渲染也不必重新加载页面。如果我将一个远程设置为true,那么这意味着一个将自动重新加载而另一个不会。关于如何使两个远程trues同时工作的任何建议?这是我第一次这样做。

这是我的第一个用户可以发表评论的视图

<%= form_for [@part, Comment.new], remote: true do |f|%>
        <div>
          <%= f.text_area :content %>
          <%= f.submit "Post Comment"%>
        </div>
        <%end%>

用户如何删除评论

<%=link_to 'delete', part_comment_path(@part, comment), data: {confirm: "Are you sure you want to delete this comment?"}, remote: true, method: :delete%>

和create.js.erb

$('.comments').append("<%= j(render @comment) %>")

感谢任何能解释如何解决此问题的人

UPDATE 这是我的评论控制器

class CommentsController < ApplicationController
  def create
    part = Part.find(params[:part_id])
    @comment = part.comments.create(comment_params.merge(user: current_user))

    respond_to do |format|
      format.html {redirect_to @part}
      format.js{}
  end
end

  def destroy
    @part = Part.find(params[:part_id])
    @comment = @part.comments.find(params[:id])
    @comment.destroy

    respond_to do |format|
      format.html {redirect_to @part}
      format.js{}
    end
  end

private
def comment_params
  params.require(:comment).permit(:content)
  end
end

这是我的评论路线

resources :parts do
    resources :comments, only: [:create, :destroy]
  end

以防万一

以下是我的日志

ActionView::Template::Error (No route matches {:action=>"destroy", :controller=>"comments", :id=>"52", :part_id=>nil} missing required keys: [:part_id]):
    1: <li><%= comment.content%> by: <%= comment.user.first_name %> </li>
    2: <% if logged_in? %>
    3: <%=link_to 'delete', part_comment_path(@part, comment), remote: true, data: {confirm: "Are you sure you want to delete this comment?"}, method: :delete%>
    4: <%end%>
  app/views/comments/_comment.html.erb:3:in `_app_views_comments__comment_html_erb___3749430301288060826_70216407028000'
  app/views/comments/create.js.erb:1:in `_app_views_comments_create_js_erb___1584098095545825378_70216383980080'

这似乎是问题....我不明白这是如何缺少part_id的。

我的日志中的错误的屏幕截图

enter image description here

_comment.html.erb view

<li><%= comment.content%> by: <%= comment.user.first_name %> </li>
<% if logged_in? %>
<%=link_to 'delete', part_comment_path(@part, comment), remote: true, data: {confirm: "Are you sure you want to delete this comment?"}, method: :delete%>
<%end%>

1 个答案:

答案 0 :(得分:0)

试试这个:

 def destroy
   @part = Part.find(params[:part_id])
   @comment = Comment.find(params[:id])
   if @comment.destroy
     respond_to do |format|
       format.html
       format.js
     end
   end
 end

如果找不到part_id,请尝试:

<%=link_to 'delete', part_comment_path(id: comment.id), remote: true, data: {confirm: "Are you sure you want to delete this comment?"}, method: :delete%>  


def destroy
   @comment = Comment.find(params[:id])
   if @comment.destroy
     respond_to do |format|
       format.html
       format.js
     end
   end
 end