Rails控制器名称带有破折号而不是下划线

时间:2022-07-29 21:15:13

Is it possible to forces Rails to use dashes (-) instead of underscores when referring to controllers.

当引用控制器时,是否可以强制Rails使用短划线( - )而不是下划线。

There currently exists a nice function of the Inflector called parameterize. It allows for very nice permalinks with all special characters removed and replaced with dashes...

目前存在称为参数化的Inflector的一个很好的功能。它允许非常好的永久链接删除所有特殊字符并用短划线替换...

However, when using controllers that have multiple words (like contact_methods_controller.rb for example), you define your route:

但是,当使用具有多个单词的控制器(例如contact_methods_controller.rb)时,您可以定义路径:

resources :contact_methods

This creates a map to /contact_methods (NOT /contact-methods). When I mix these two, I get ugly URLs like:

这将创建/ contact_methods(NOT / contact-methods)的映射。当我混合这两个时,我会得到丑陋的URL:

/contact_methods/1-preferred-email

I'd like to have Rails map controllers with dashes instead of underscores. All my research says to individually map each controller:

我想让Rails地图控制器使用破折号而不是下划线。我所有的研究都说要分别映射每个控制器:

match 'contact-methods(/:action)' => 'contact_methods'

but that is really stupid, in my opinion, and it becomes messy if I'm nesting resources... I shouldn't have to define these as custom routes. Is there a setting in ActionDispatch that automatically rewrites these things? I can't find one...

但在我看来,这真的是愚蠢的,如果我在嵌套资源,它会变得混乱......我不应该将它们定义为自定义路径。 ActionDispatch中是否有自动重写这些内容的设置?我找不到一个......

1 个解决方案

#1


10  

In your route.rb

在你的route.rb

resources "contact-methods", :controller => :contact_methods, :as => :contact_methods

Edit: You have to specify the :as => ... path or else ActionDispatch throws a fit...

编辑:你必须指定:as => ... path或者否则ActionDispatch会抛出一个拟合...

#1


10  

In your route.rb

在你的route.rb

resources "contact-methods", :controller => :contact_methods, :as => :contact_methods

Edit: You have to specify the :as => ... path or else ActionDispatch throws a fit...

编辑:你必须指定:as => ... path或者否则ActionDispatch会抛出一个拟合...