簡體   English   中英

Rails 路線:嵌套范圍的順序

[英]Rails routes: Order of nested scopes

所以我有一條更復雜的路線,而且我對兩個嵌套范圍的順序有疑問。 他們的順序似乎顛倒了。 我希望最內部的 scope 成為 URL 動作前的最后一段。 但這是第一個。

路線.rb

namespace :customer do
  namespace :api do
    resources :products, only: [], param: :uid do
      scope module: 'products' do
        scope :buyer do
          post :set_to_waiting_list, to: 'buyers#set_to_waiting_list'
        end
      end
    end
  end
end

Controller:

module Customer
  module Api
    module Products
      class BuyersController < Customer::ApiController
        def set_to_waiting_list
          # do stuff
        end
      end
    end
  end
end

這在運行rake routes

customer_api_product_set_to_waiting_list POST /customer/api/buyer/products/:product_uid/set_to_waiting_list(.:format) customer/api/products/buyers#set_to_waiting_list

但我實際上正在尋找的 URL 是:

POST /customer/api/products/:product_uid/buyer/set_to_waiting_list

原因是這會修改買家而不是產品。 此外,買家是通過產品 uid(加上登錄用戶)獲取的,因此這種 URL 格式更有意義。

我真的不明白

我仍然對這背后的邏輯感興趣。 但是對於任何尋求解決方案的人,我只是通過以下方式解決了它:

namespace :customer do
  namespace :api do
    resources :products, only: [], param: :uid do
      scope module: 'products' do
        post :set_to_waiting_list, path: 'buyer/set_to_waiting_list' to: 'buyers#set_to_waiting_list'
      end
    end
  end
end

您需要添加一個nested塊,以便 scope 知道在哪里放置路徑前綴:

  namespace :customer do
    namespace :api do
      scope module: 'products' do
        resources :products, only: [], param: :uid do
          nested do
            scope :buyer do
              post :set_to_waiting_list, to: 'buyers#set_to_waiting_list'
            end
          end
        end
      end
    end
  end

nested沒有記錄,所以我不確定你是否應該依賴這個。 作為替代方案,您可以添加resource:buyers, only: [] {}包裝器:

  namespace :customer do
    namespace :api do
      scope module: 'products' do
        resources :products, only: [], param: :uid do
          resource :buyer, only: [] do
            collection do
              post :set_to_waiting_list
            end
          end
        end
      end
    end
  end

在這兩種情況下,路由和 controller 相同,但 URL 助手不同:

customer_api_product_set_to_waiting_list
POST /customer/api/products/:product_uid/buyer/set_to_waiting_list(.:format)
customer/api/products/buyers#set_to_waiting_list

對比

set_to_waiting_list_customer_api_product_buyer
POST /customer/api/products/:product_uid/buyer/set_to_waiting_list(.:format)
customer/api/products/buyers#set_to_waiting_list

來源: https://github.com/rails/rails/issues/12626

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM