如何使用FORM创建DELETE路由及其功能

时间:2017-10-07 20:29:59

标签: ruby-on-rails ruby routes

这是我得到的错误

  

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

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

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

1 个答案:

答案 0 :(得分:0)

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

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

您不应该手工制作HTML。

您真的需要阅读Guideapi doc(向下滚动到&#34; form_for与模型对象&#34;)。