如何在 rails 中添加单个自定义路由?

How to add a single custom route in rails?

我有一个 'transaction' 模型、控制器和视图,它们是我用 rails 生成的。现在我需要将 /transactions/history 的单个自定义路由添加到我的应用程序以由控制器 def history 处理:...结束并呈现 history.html.erb

所以在我的 routes.rb:

中添加了这一行
get '/transactions/history', to: 'transactions#history', as: 'transactions_history'

这是我的 transactions_controller.rb:

def history
    @transactions = Transaction.all
end

并在事务中创建了一个 history.htmk.erb->views

我在调用 rake 路由时也看到了这一行:

transactions_history GET    /transactions/history(.:format)                 transactions#history

但是当我在浏览器中请求 localhost:3000/transactions/history 时,出现以下错误:

Couldn't find Transaction with 'id'=history

(因为我的控制器里有这一行)

before_action :set_transaction, only: [:show, :edit, :update, :destroy])

而且我还在日志中看到了这一行:

Request info

Request parameters  
{"controller"=>"transactions", "action"=>"show", "id"=>"history"}

我的完整路线: routes.rb 我的全部错误: error logs 为什么它在我的事务控制器中调用 'show' 操作?

在您的 routes.rb 中,rails 脚手架生成器应该添加了一个 resources :transactions。这将为您生成 7 条路线,其中之一是 /transactions/:id,对应于 TransactionsController.

中的 show 动作

Rails按照routes.rb定义的顺序匹配路由,会调用第一个匹配路由的controller action。

我猜你在 resources :transactions 下面定义了 get '/transactions/history', to: 'transactions#history', as: 'transactions_history'。当您传递 /transactions/history 时,这是调用 show 操作,其中 :id 匹配 history.

要解决此问题,有 2 个解决方案:

首先,将您的自定义路线移到 resources :transactions 上方。

或者像这样扩展 resources 声明并删除您的自定义路由:

resources :transactions do
  collection do
    get :history
  end
end

是因为你的路由与默认资源路由冲突,具体是GET transactions/:id

resources :transactions do
  get :history, on: :collection
end

http://guides.rubyonrails.org/routing.html#adding-collection-routes

您也可以试试:

  1. 切换路由的定义顺序,或者
  2. 正在更改您的自定义路线以使其不冲突,例如而不是 /transactions/history 尝试 /transaction_history 或其他东西。