ruby-on-rails 参数错误的路由

b5lpy0ml  于 2023-11-20  发布在  Ruby
关注(0)|答案(2)|浏览(129)

我有以下路线:

resources :users, only: [] do
  resources :events, only: %i[index]
  delete :close_account, on: :member
end

字符串
由于某些原因,它生成具有不同参数的路由:

GET      /backoffice/users/:user_id/events(.:format)               backoffice/events#index
       DELETE   /backoffice/users/:id/close_account(.:format)             backoffice/users#close_account


在一个路由中,参数是user_id,下面的路由是id。我希望两者都是user_id,所以我添加了resources :users, param: :user_id
现在的路线比以前更奇怪了

GET      /backoffice/users/:user_user_id/events(.:format)          backoffice/events#index
      DELETE   /backoffice/users/:user_id/close_account(.:format)        backoffice/users#close_account


我如何修复这个路由,使两个路由都有相同的参数?

snvhrwxg

snvhrwxg1#

参数没有“错误”。您看到此行为的原因是id参数名称在这里保留给最里面的资源。也就是说,如果您的EventsController除了index之外还有其他操作,它将接收事件ID为id,而相关的User ID将是user_id。其他路由不是嵌套资源,因此不需要不同的前缀。
这可以在Rails指南中关于嵌套资源的部分看到。
也就是说,如果您真的希望两者都被称为user_id,则应该使用

delete "/backoffice/users/:user_id/close_account/", to: "backoffice/users#close_account"

字符串

mfuanj7w

mfuanj7w2#

我同意,这绝对是令人困惑的。利用Rails插装的最简单的解决方案是使用资源两次,一次没有指定参数名,另一次使用它:

resources :users, only: [] do
  resources :events
end
resources :users, param: :user_id

字符串
一般情况下,

resources :users, param: :number do
  resources :events
end
resources :users, param: :user_number


这将产生

GET    /users/:user_number/events(.:format)          /events#index
POST   /users/:user_number/events(.:format)          /events#create
GET    /users/:user_number/events/new(.:format)      /events#new
GET    /users/:user_number/events/:id/edit(.:format) /events#edit
GET    /users/:user_number/events/:id(.:format)      /events#show
PATCH  /users/:user_number/events/:id(.:format)      /events#update
PUT    /users/:user_number/events/:id(.:format)      /events#update
DELETE /users/:user_number/events/:id(.:format)      /events#destroy
GET    /users/new(.:format)                          /users#new
GET    /users/:user_number/edit(.:format)            /users#edit
GET    /users/:user_number(.:format)                 /users#show
PATCH  /users/:user_number(.:format)                 /users#update
PUT    /users/:user_number(.:format)                 /users#update
DELETE /users/:user_number(.:format)                 /users#destroy


如果你更喜欢在模块中 Package 控制器,请使用作用域。

相关问题