不路由到预期的控制器操作,Rails

东区开发
Rails 6

在我的 config/routes.rb 中,我有:

match "customers/current_customers" => "customers#current_customers", as: :current_customers, via: [:get]

在我的下拉菜单中,我有:

.dropdown-menu aria-labelledby="Customers"
  button.dropdown-item type="button"
    = link_to current_customers_path
      = t('current_customers')

我的路线,显示:

customers GET /customers(.:format) customers#index 
POST /customers(.:format) customers#create 
new_customer GET  /customers/new(.:format) customers#new 
edit_customer GET  /customers/:id/edit(.:format)   customers#edit 
customer GET  /customers/:id(.:format) customers#show 
PATCH  /customers/:id(.:format) customers#update 
PUT  /customers/:id(.:format) customers#update 
DELETE /customers/:id(.:format) customers#destroy 
current_customers GET  /customers/current_customers(.:format)   customers#current_customers 

和。在控制器/customers_controller.rb 中,我有:

def current_customers
  @customers = Customer.current_customers
end

当我选择菜单项时,开发日志告诉我:

Started GET "/customers/current_customers" for 127.0.0.1 at 2020-03-13 18:04:15 -0700
Processing by CustomersController#show as HTML
  Parameters: {"id"=>"assigned_customers"}

显然,这失败了,并显示以下消息:

ActiveRecord::RecordNotFound (Couldn't find Customer with 'id'=current_customers):  
app/controllers/customers_controller.rb:86:in `set_customer'

为什么要执行show操作,而不是 current_customers?

乔什·布罗迪

您的路线从上到下进行处理,并且优先考虑那些在顶部的路线。

假设你也有一个resources :customers,然后在这下面是match ...,优先考虑match应该让你得到你正在寻找的结果。此外,使用collection

match "customers/current_customers" => "customers#current_customers", as: :current_customers, via: [:get]
resources :customers

或(首选)

resources :customers do 
  collection do 
    get :current_customers
  end 
end

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章