【问题标题】:How to create a DELETE route and its function with a FORM如何使用 FORM 创建 DELETE 路由及其功能
【发布时间】:2017-10-07 20:29:59
【问题描述】:

这是我遇到的错误

没有路线匹配 [POST] "/questions/1"

这是控制器代码 我试图在使用按钮时删除问题 我知道路由是/question/:id,方法是POST,方法名需要destroy

class QuestionsController < ApplicationController
skip_before_action :verify_authenticity_token, :only => :create

def index
@questions = Question.all
end

def show  
id = params[:id]
@question = Question.find(id)
@answers = Answer.all
end 

def destory 
@question = Movie.delete(params[:id])
redirect_to "/questions"
end 

def create 
Question.create(title: params[:title], content: params[:content])
redirect_to "/questions"
end
end

这是html表单是删除表单

<div>
Title:<br>
<%= @question.title%><br>
Question:<br>
<%= @question.content%><br><br>
<form action="/questions/<%=@question.id%>" method="POST">
<input  type="hidden" name="method" value="DELETE">
<input type="submit" value="Delete Question">
</form>

<% @answers.each do |answer| %>
<% if answer.question_id == @question.id %>
Title:<br>
<%= answer.title%><br>
Answer:<br>
<%= answer.content%>
<%end%>
<%end%>  

<form>
<input type="text" name="title" placeholder="Title"><br>
<input type="text" name="content" placeholder="Answer">
<input type="submit" name="submit">
</form>
</div>

routes.rb

Rails.application.routes.draw do
resources :questions
end

【问题讨论】:

  • 那是什么? erb 加上一些手工制作的 HTML?为什么不使用表单助手?
  • 不确定什么是表单助手,我刚从 Active Record 和 ruby​​ 中脱离出来,我正进入 Rails 世界试图解决这个问题。
  • 显示您的路线文件。你也拼写了destroy destory
  • 您不需要表单,只需使用方法 delete 使用link_to helper 创建一个链接。
  • @Maxence - 好点!而且是真的。我被那种混搭弄得晕头转向了。

标签: ruby-on-rails ruby routes


【解决方案1】:

假设您的路线设置正确,您应该执行以下操作:

<%= form_for @question, method: :delete do |f| %>
  ...
<% end %>

您不应该手工制作该 HTML。

您确实需要阅读Guideapi doc(向下滚动到“带有模型对象的form_for”)。

【讨论】:

  • 如果你能详细介绍一些细节来帮助我,那将是很棒的!
  • 用您尝试过的内容更新您的问题。以及您在控制台中遇到的任何错误。
猜你喜欢
  • 2022-12-13
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
  • 2016-07-03
  • 1970-01-01
  • 2014-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多