没有路线匹配[POST]“/ projects / 16 / todos / 35 / edit”
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了没有路线匹配[POST]“/ projects / 16 / todos / 35 / edit”相关的知识,希望对你有一定的参考价值。
我收到了这个错误
没有路线匹配[POST]“/ projects / 16 / todos / 35 / edit”
我知道我不必为此设置方法,但如何添加它
这是routes.rd
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get 'projects/index'
post 'projects/new'
resources :projects do
resources :todos
end
root 'projects#index'
end
这是edit.html.erb(用于任务)
<h1>Edit Task</h1>
<%= form_for :todo, local: true do |form| %>
<p>
<%= form.label :body %><br>
<%= form.text_field :body %>
</p>
<div>
<%= form.submit%>
</div>
<% end %>
这是todos_controller.rb
class TodosController < ApplicationController
def new
@project = Project.find(params[:project_id])
end
def create
@project = Project.find(params[:project_id])
@todo = @project.todos.create(todos_params)
redirect_to projects_path
end
def edit
@project = Project.find(params[:project_id])
@todo = @project.todos.find(params[:id])
end
def update
@project = Project.find(params[:project_id])
@todo = @project.todos.find(params[:id])
@todo.save
end
def destroy
@project = Project.find(params[:project_id])
@todo = @project.todos.find(params[:id])
@todo.destroy
redirect_to projects_path
end
private
def todos_params
params.require(:todo).permit(:body)
end
end
请帮助解决这个问题
答案
正如您在此处所看到的,触发的请求是POST请求,而应该是GET请求
收到此错误没有路由匹配[POST]“/ projects / 16 / todos / 35 / edit”
确保在单击“编辑TODO”时触发GET请求。
定义路线
resources :projects do
resources :todos
end
是
project_todos GET /projects/:project_id/todos(.:format) todos#index
POST /projects/:project_id/todos(.:format) todos#create
new_project_todo GET /projects/:project_id/todos/new(.:format) todos#new
edit_project_todo GET /projects/:project_id/todos/:id/edit(.:format) todos#edit
project_todo GET /projects/:project_id/todos/:id(.:format) todos#show
PUT /projects/:project_id/todos/:id(.:format) todos#update
DELETE /projects/:project_id/todos/:id(.:format) todos#destroy
因此,您可以在link_to中使用rails视图帮助程序edit_project_todo(project,todo)来编辑TODO以触发GET请求。
另一答案
在您的edit.html.erb中
<h1>Edit Task</h1>
<%= form_for @todo, :url => project_todo_path(@project,@todo), :html => { class: "your_class", :method => "put" } do |form| %>
<p>
<%= form.label :body %><br>
<%= form.text_field :body %>
</p>
<div>
<%= form.submit%>
</div>
<% end %>
注意: - form_for
用于任何对象,并且在这里你的对象是@todo
而不是todo
,默认情况下form_for
命中create
动作如果@todo
是新的,如果@todo
是现有记录那么它将命中更新动作,这里明确你可以提供url
到提交表格后会触及哪个动作。所以在这里我手动提供更新的动作,并提供method: :put
,因为默认情况下form
是POST
类型请求。希望它能清除你的怀疑。
以上是关于没有路线匹配[POST]“/ projects / 16 / todos / 35 / edit”的主要内容,如果未能解决你的问题,请参考以下文章