我是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)
答案 0 :(得分:0)
更改重定向路径
redirect_to puzzles_path
答案 1 :(得分:0)
您的代码中存在以下几个问题:
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_path
3)但最重要的是。与method: 'delete'
的链接仅适用于JavaScript和Rails 5.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
确保在您的浏览器中确保加载文件时没有错误。