Rails路线和控制器参数 [英] Rails routes and controller parameters

查看:69
本文介绍了Rails路线和控制器参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拥有共享同一控制器的这两个资源.到目前为止,我的方法是使用特殊的类型参数进行路由:

I have those two resources which share the same controller. So far, my approach was routing with an special type parameter:

resources :bazs do
  resources :foos, controller: :foos, type: :Foo
  resources :bars, controller: :foos, type: :Bar
end

路线按预期运行,但是我所有的链接都像这样:

The routes work as expected, but all my links are like this:

/bazs/1/foos/new?type=Foo
/bazs/1/bars/new?type=Bar

代替

/bazs/1/foos/new
/bazs/1/bars/new

如何在不弄乱链接的情况下将参数传递给控制器​​?

How do I pass parameters to the controller without messing the links?

推荐答案

尝试如下操作:

resources :bazs do
  get ':type/new', to: 'foos#new'
end

对于需要2个ID的动词,

For the verbs in which you need 2 IDs,

resources :bazs do
  get ':type/:id', to: 'foos#show', on: :member
end

然后您同时拥有params [:bazs_id]和params [:id].

Then you have both params[:bazs_id] and params[:id].

您也可以这样做:

resources :bazs do
  member do
    get ':type/new', to: 'foos#new'
    get ':type/:id', to: 'foos#show'
  end
end

为了始终具有params [:bazs_id].

in order to always have params[:bazs_id].

对于您提到的根级别冲突,可以执行以下操作:

For the root level conflicts you mentioned, you can do something like:

constraints(type: /foos|bars/) do
  get ':type/new', to: 'foos#new'
  get ':type/:id', to: 'foos#show'
end

这篇关于Rails路线和控制器参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆