我是Ruby on rails的初学者,当我尝试删除我创建的对象时失败了。下面是代码。controller
class PuzzlesController < ApplicationController
def index
@puzzles = Puzzle.all
end
def show
@puzzle=Puzzle.find(params[:id])
end
def new
@puzzle = Puzzle.new
end
def create
#render plain: params[:puzzle].inspect
@puzzle = Puzzle.new(puzzle_params)
if(@puzzle.save)
redirect_to @puzzle
else
render 'new'
end
end
def edit
@puzzle=Puzzle.find(params[:id])
end
def update
@puzzle=Puzzle.find(params[:id])
if(@puzzle.update(puzzle_params))
redirect_to @puzzle
else
render 'edit'
end
end
def destroy
@puzzle = Puzzle.find(params[:id])
@puzzle.destroy
redirect_to puzzle_path
end
private def puzzle_params
params.require(:puzzle).permit(:title,:body,:category,:difficulty)
end
end<h2><%= @puzzle.title %></h2>
<p><%= @puzzle.body %></p>
<p><%= @puzzle.category %></p>
<p><%= @puzzle.difficulty %></p>
<hr>
<%= link_to "Edit", edit_puzzle_path(@puzzle), :class => 'btn btn-default'%>
<%= link_to "Delete", puzzle_path(@puzzle),
method: :delete,
data: {confrim: 'are you sure? '},
:class => 'btn btn-danger'%>当我点击删除时,就像重新渲染页面一样。我在网上找了很久,也找不到解决方案。
这是rails服务器上的信息。
Started GET "/puzzles/1" for ::1 at 2017-04-02 18:51:18 +0930
Processing by PuzzlesController#show as HTML
Parameters: {"id"=>"1"}
Puzzle Load (0.5ms) SELECT "puzzles".* FROM "puzzles" WHERE "puzzles"."id" = ? LIM IT ? [["id", 1], ["LIMIT", 1]]
Rendering puzzles/show.html.erb within layouts/application
Rendered puzzles/show.html.erb within layouts/application (1.0ms)
Completed 200 OK in 63ms (Views: 46.2ms | ActiveRecord: 0.5ms)发布于 2017-04-02 17:14:59
更改您的重定向路径
redirect_to puzzles_path发布于 2017-04-02 17:34:15
您的代码中有几个问题:
1) link_to参数列表有拼写错误(confirm,不是confrim):
<%= link_to 'Delete', puzzle_path(@puzzle),
method: :delete,
data: { confirm: 'are you sure? '},
class: 'btn btn-danger' %>2)在destroy方法的末尾,您不能重定向到单一的益智路径,因为您刚刚删除了该益智。重定向至索引页:
redirect_to puzzles_path3)但最重要的是。与method: 'delete'的链接只适用于JavaScript,而Rails5.0依赖于jQuery。因为您编写的链接只是重定向到显示页面,所以我猜您还没有将Rails JavaScript文件包含到您的资产管道中:
# Add this to the head of your `views/layout/application.rb`:
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
# Ensure that your `assets/javascripts/application.js` include the following lines:
//= require jquery
//= require jquery_ujs确保在浏览器的concole中加载文件时没有错误。
https://stackoverflow.com/questions/43166412
复制相似问题