rails嵌套表单中的路由错误

时间:2017-04-12 00:13:24

标签: ruby-on-rails-5 nested-forms

我目前正在开展我的项目,但面临一些挑战。我有一个项目模型,其中嵌入了Comment对象我可以创建一个新的注释但是当我尝试编辑与项目对象关联的注释时,我在浏览器中看到这个奇怪的错误,表明我正在尝试编辑注释属于不存在的项目。实际上当我检查url时,项目的id并不存在。例如,如果我想编辑属于id为1的项目的注释,则错误消息表明我想编辑属于具有id 2的项目的注释。我已经尝试了所有我知道的但是可以'找到问题的根源。 这就是我的评论控制器的样子

[8点04] class CommentsController< ApplicationController的   before_action:find_project

def index
    @projects = Project.all
    if params[:project_id]
      @comments = @project.comments.all
      redirect_to @comments
    end
  end



 def new
    if params[:project_id]
    @project = Project.find(params[:project_id])
    @comment = @project.comments.build
    end
  end

 def create
  if params[:project_id]
   @project = Project.find(params[:project_id])

   @comment = @project.comments.create(comment_params)
    if @comment.save
      redirect_to @comment
    else
      render "new"
    end
   end
  end

 def show
    if params[:project_id]
    @project = Project.find_by(:id => params[:id])
    @comment = @project.comments.find_by(:id => params[:id])

 end
end

 def edit
    if params[:project_id]
    @comment = @project.comments.find_by(:id => params[:id])
  end
 end

 def update
    if params[:project_id]
    @comment = @project.comments.find_by(:id => params[:id])
    @comment.update(comment_params)
      redirect_to @comment

     render "edit", notice: "You cannot update the comment"
    end
  end

 def destroy
    @comment = @project.comments.find_by(:id => params[:id])
    @comment.destroy
    flash[:notice] = "Comment has been successfully deleted"
    redirect_to @project
  end

 private

  def find_project
    @project = Project.find_by(id: params[:project_id])
  end

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

end

1 个答案:

答案 0 :(得分:0)

在show方法中,您使用了params [:id]作为project_id

@project = Project.find_by(:id => params[:id])

尝试将其更改为

 @project = Project.find_by(:id => params[:project_id])