我希望标题不会误导,因为我不知道我正在处理的问题有更好的标题:
我有一位属于所在地和专业的医生。我想路由以显示doc控制器的动作,如下所示:
/牙医/柏林/ 7
我定义了这样的路线:
get ':specialty/:location/:id', to: 'docs#show'
在我的视图中,创建以下URL以链接到doc控制器的show动作:
<%= link_to doc.name, "#{doc.specialty.name}/#{doc.location.name}/#{doc.id}" %>
这是解决问题的好方法吗?如果没有,是否有更简洁的方法来构建这样可能使用资源的网址?这个问题到底是什么名字?
非常感谢您的帮助。
答案 0 :(得分:1)
正确的方法是为您的路线命名,如下所示:
get ':specialty/:location/:id', to: 'docs#show', as: 'docs_show'
然后你可以像这样使用它:
<%= link_to doc.name, docs_show_path(doc.specialty.name, doc.location.name, doc.id) %>
注1:
Rails在您定义的路由名称的末尾附加_path
。
注2:
您可以通过执行rake routes
来查看所有可用的命名路由。
答案 1 :(得分:1)
有关参考资料,您应该查看this page(尤其是the end of section 2.6)
如果它只适用于单一路线,那就好了。但是如果你想拥有多条路线(例如/dentist/berlin/7
,/dentist/berlin/7/make_appointment
等),你可能需要构建更多的路线,以便利用铁路resources
。
例如,而不是
get ':specialty/:location/:id', to: 'doctors#show'
get ':specialty/:location/:id/appointment', to: 'doctors#new_appointment'
post ':specialty/:location/:id/appointment', to: 'doctors#post_appointment'
你可以有这样的东西(代码几乎相同,见下面的解释)
resources :doctors, path: '/:specialty/:location', only: [:show] do
member do
get 'new_appointment'
post 'create_appointment'
end
end
<强>解释强>
resources
将为指定的控制器生成RESTful路由(索引,显示,编辑,新建,创建,销毁)(我假设为doctors_controller
)然后你要添加member
个动作,即。可以对集合的特定项执行的操作。您可以选择不同的语法
resources :doctors do
member do
# Everything here will have the prefix /:id so the action applies to a particular item
end
end
# OR
resources :doctors do
get 'new_appointement', on: :member
end
默认情况下,控制器操作与您提供的路径名相同,但您也可以覆盖它
member do
get 'appointment', action: 'new_appointment'
post 'appointment', action: 'post_appointment'
end
Rails在路由方面有一些很棒的帮助!