Rails - ActionController :: UrlGenerationError没有路由匹配缺少必需的键:[:id]

时间:2017-05-22 10:20:25

标签: ruby-on-rails ruby model-view-controller

在尝试将编辑功能实现到评论MVC流程时,我在Rails应用程序中收到了上述错误。

这是出现错误的视图代码 -

_comments.html.erb

<% if user_signed_in?  %>
      <p><%= link_to "Edit", edit_event_comment_path(@event, comment), remote: true %></p>
      <p><%= link_to 'Delete', [comment.event, comment],
                  method: :delete,
                  class: "button",
                  data: { confirm: 'Are you sure?' } %></p>
      <% end %>

这是注释控制器代码 -

Comments_controller.rb

class CommentsController < ApplicationController
    before_action :set_comment, only: [:show, :edit, :update, :destroy]


    def create
        @event = Event.find(params[:event_id])
        @comment = @event.comments.create!(params[:comment].permit(:name, :body))
        @comment.user_id = current_user.id


        redirect_to @event
    end

    # GET /comments/1/edit
    def edit
        respond_to do |f|
            f.js 
            f.html 
        end
    end

    def update


        respond_to do |format|
            if @comment.update
                format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
                format.js   { }
                format.json { render :show, status: :created, location: @comment }
            else
                format.html { render :new }
                format.json { render json: @comment.errors, status: :unprocessable_entity }
            end
        end
    end



    def destroy
        @event = Event.find(params[:event_id])
        @comment = @event.comments.find(params[:id])
        @comment.destroy

        redirect_to event_path(@event)
    end

    private
    # Use callbacks to share common setup or constraints between actions.
    def set_comment
      @comment = Comment.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def comment_params
      params.require(:comment).permit(:event_id, :body)
    end


end

以下是我的路线 - enter image description here

我将注释设置为事件的嵌套路由,因此路径路径是正确的。我尝试了一些不同的变体作为试错,但我仍然遇到错误。我确定答案是盯着我的脸,但我需要来自不同眼睛的帮助。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

根据您的代码,如果您没有循环@comments

comment应为@comment

<% if user_signed_in?  %>
      <p><%= link_to "Edit", edit_event_comment_path(@event, @comment), remote: true %></p>
      <p><%= link_to 'Delete', [@comment.event, @comment],
                  method: :delete,
                  class: "button",
                  data: { confirm: 'Are you sure?' } %></p>
 <% end %>

另外,将您的编辑操作更改为

   def edit
        @event = @comment.event
        respond_to do |f|
            f.js 
            f.html 
        end
    end