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

Bar*_*ian 5 ruby model-view-controller ruby-on-rails ruby-on-rails-3

我有一个'事务'模型,控制器和视图,我用rails generate创建.现在我需要向我的应用程序添加一个/ transactions/history的自定义路由,由控制器def历史记录处理:... end和render history.html.erb

所以在我的routes.rb中添加了这一行:

get '/transactions/history', to: 'transactions#history', as: 'transactions_history'
Run Code Online (Sandbox Code Playgroud)

这在我的transactions_controller.rb中:

def history
    @transactions = Transaction.all
end
Run Code Online (Sandbox Code Playgroud)

并在transactions-> views中创建了history.htmk.erb

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

transactions_history GET    /transactions/history(.:format)                 transactions#history
Run Code Online (Sandbox Code Playgroud)

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

Couldn't find Transaction with 'id'=history
Run Code Online (Sandbox Code Playgroud)

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

before_action :set_transaction, only: [:show, :edit, :update, :destroy])
Run Code Online (Sandbox Code Playgroud)

我也在日志中看到这一行:

Request info

Request parameters  
{"controller"=>"transactions", "action"=>"show", "id"=>"history"}
Run Code Online (Sandbox Code Playgroud)

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

AbM*_*AbM 5

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

Rails 按照 中定义的顺序匹配路由,routes.rb并将调用第一个匹配路由的控制器操作。

我猜你的情况你定义get '/transactions/history', to: 'transactions#history', as: 'transactions_history'如下resources :transactions。当您通过时/transactions/history,这是调用show具有:id匹配的操作history

为了解决这个问题,有两种解决方案:

首先,将您的自定义路由移到resources :transactions.

或者扩展resources声明并删除您的自定义路由,如下所示:

resources :transactions do
  collection do
    get :history
  end
end
Run Code Online (Sandbox Code Playgroud)