Rails 嵌套资源忽略单个路由

Rails nested resources ignore single route

我的路由中有一个 rails 嵌套资源。

resources :users do
  resources :accounts
end

resources :accounts

上市操作当然是:

GET /users
GET /users/:user_id/accounts

我想摆脱 /users 路线但保留 /users/:id/accounts 路线。

知道我该怎么做吗?谢谢

设置only: []然后rails路由将根据需要生成/users/:id/accounts

resources :users, only: [] do
 resources :accounts # , only: [:index] if you just only keep users/:id/accounts
end
# if you only want to get rid of GET /users
resources :users, except: [:index]
# if you mean you want to get rid all of /users routes (not just only GET /users) then comment above line

这就是 scope 的目的

scope :users do 
  resources :accounts
end

Rails guides on routing

或者您可以使用这两种相同的方式,使用 namespacescope:

  namespace :users do
    scope ':user_id' do
      resources :accounts
    end
  end

仅使用 scope:

  scope ':users/:user_id' do
    resources :accounts
  end

不使用except: [:index]将限制两条路线。这是一个荒谬的说法,可以很容易地被 运行 rails routes 反驳。 None resources 的选项“滴入”嵌套调用。

resources :users, only: [] do
  resources :accounts, only: :index
end

only: [] 跳过所有“用户”路由的生成。

这将生成路线:

Prefix        Verb   URI Pattern                          Controller#Action
user_accounts GET    /users/:user_id/accounts(.:format)   accounts#index
# ...

请注意,参数键是 :user_id 而不是 :id。如果你真的想打破你需要做的约定:

# don't do this - its stupid
scope '/users/:id', as: :user do
  resources :accounts, only: :index
end