如何在rails中命名路线 [英] How to name a route in rails

查看:47
本文介绍了如何在rails中命名路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些看起来像这样的路线:

I have some routes looking like this :

match 'hotels/:action(/:id)', :controller => 'hotel', :action => /[a-z]+/i, :id => /[0-9]+/i

我想在我的代码中的某处使用类似 hotels_dislike_path 的东西,它指的是/hotels/dislike

And i want to use something like hotels_dislike_path somewhere in my code which refers to /hotels/dislike

我该怎么做?

推荐答案

来自 路由指南:

您可以使用 :as 选项为任何路由指定名称.

3.6 Naming Routes

You can specify a name for any route using the :as option.

match 'exit' => 'sessions#destroy', :as => :logout

所以,在你的情况下,那就是:

So, in your case, that would be:

match 'hotels/:action(/:id)', :controller => 'hotel', :action => /[a-z]+/i, :id => /[0-9]+/i
match 'hotels/dislike(/:id)', :controller => 'hotel', :id => /[0-9]+/i, :as => :hotels_dislike
match 'hotels/like(/:id)', :controller => 'hotel', :id => /[0-9]+/i, :as => :hotels_like

我认为没有办法动态执行此操作(因此基本上您必须为每个操作定义一个路由).但是,您可以为最常用的操作定义几个路由(如上),只需使用 hotels_path :action =>;:really_like 用于更不常见的操作.

I don't think there's a way to do this dynamically (so you have to define one route for each action, basically). However, you can just define a couple of routes (like above) for the most used actions, and just use hotels_path :action => :really_like for more uncommon actions.

这篇关于如何在rails中命名路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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