【问题标题】:Rails 4 - How to route delete pathRails 4 - 如何路由删除路径
【发布时间】:2014-11-29 18:59:58
【问题描述】:

我一直在使用 Rails 3,并且正在尝试使用 Rails 4。我正在这里学习 ToDo 教程:http://www.codelearn.org/ruby-on-rails-tutorial/introduction-views-layouts-helpers-assets-pipeline

我正在尝试使用 Rails 'link_to' 辅助方法删除 ToDo 项,并且一直在网上查找,但在过去 90 分钟内无法使其正常工作,因此我决定寻求帮助。

这是我收到的错误消息:

Routing Error
No route matches [DELETE] "/todos/delete_path"

这是我从航站楼的“耙路线”:

Prefix Verb   URI Pattern             Controller#Action
 todos_index GET    /todos/index(.:format)  todos#index
todos_delete DELETE /todos/delete(.:format) todos#delete

这是来自内部的 'link_to' 辅助方法:

index.html.erb

<%= link_to 'Delete last todo', 'delete_path', method: :delete %>

这是我的:

routes.rb

Rails.application.routes.draw do
  get 'todos/index'
  # get 'todos/delete'
  match 'todos/delete' => 'todos#delete', via: :delete

这是我的:

todos_controller.rb

class TodosController < ApplicationController
  def index
    # @todo_array = ['Buy Milk', 'Buy Soap', 'Pay bill', 'Draw Money']
    @todo_items = Todo.all
    render :index
  end

  def delete
    #put delete logic here
    @todo_items = Todo.last
    @todo_items.destroy
  end

end

感谢您花时间查看我的问题!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    你会这样写一个destroy方法:

    def destroy
      @todo = Todo.last
      @todo.destroy
      redirect_to todos_index_path #or wherever you want to redirect user after deleting the tod
    end
    

    另外,我会简单地使用 RESTful 路由:

    Rails.application.routes.draw do
      resources :todos, only: %i(index destroy)
    end
    

    【讨论】:

      猜你喜欢
      • 2014-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-13
      相关资源
      最近更新 更多