【问题标题】:scope only index action for resources资源的仅范围索引操作
【发布时间】:2020-10-11 10:33:42
【问题描述】:

我的routes.rb

Rails.application.routes.draw do
  scope :superadmin do
    resources :tenants, only: [:index]
  end

  resources :tenants, except: [:index]
end

它们产生以下路径:

tenants_path      | GET     | /superadmin/tenants(.:format) | tenants#index
                  | POST    | /tenants(.:format)            | tenants#create
new_tenant_path   | GET     | /tenants/new(.:format)        | tenants#new
edit_tenant_path  | GET     | /tenants/:id/edit(.:format)   | tenants#edit
tenant_path       | GET     | /tenants/:id(.:format)        | tenants#show

预期行为:

  • tenants#index 行动可在路线localhost:3000/superadmin/tenants
  • 所有其他tenant 操作都通过常规路线localhost:3000/tenants/*

实际行为:

当我转到tenants/new 并提交表单,从而激活tenants#create 操作时,我收到错误:

ActionController::RoutingError (No route matches [POST] "/superadmin/tenants"):

我不想发布到超级管理员,我只想发布到租户路径。为什么会这样?

【问题讨论】:

    标签: ruby-on-rails routes


    【解决方案1】:

    发生这种情况是因为 tenants#create 操作也使用了 tenants_path。

    您应该更改租户#index 或租户#create 的路径。

    最简单的做法是更新您的routes.rb

    Rails.application.routes.draw do
      scope :superadmin, as: 'superadmin' do
        resources :tenants, only: [:index]
      end
    
      resources :tenants, except: [:index]
    end
    

    它们产生以下路径:

    superadmin_tenants_path | GET   | /superadmin/tenants(.:format) | tenants#index
    tenants_path            | POST  | /tenants(.:format)            | tenants#create
    new_tenant_path         | GET   | /tenants/new(.:format)        | tenants#new
    edit_tenant_path        | GET   | /tenants/:id/edit(.:format)   | tenants#edit
    tenant_path             | GET   | /tenants/:id(.:format)        | tenants#show
    

    这样,当您提交表单并继续执行 tenants#create 操作时,它不会将您引导到超级管理员路径,并且表单将起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-06
      相关资源
      最近更新 更多