在Ruby on Rails中使用破折号`-`而不是下划线`_`进行路由 [英] Routes with Dash `-` Instead of Underscore `_` in Ruby on Rails
问题描述
我希望我的网址使用破折号-
代替下划线 _
作为单词分隔符。例如,用 controller / my-action
代替 controller / my_action
。
I want my urls to use dash -
instead of underscore _
as word separators. For example controller/my-action
instead of controller/my_action
.
我对两件事感到惊讶:
- Google等。继续区分它们。
- Ruby on Rails没有一个简单的全局配置参数来将
-
映射到_
在路由中。还是呢?
- Google et al. continue to distinguish them.
- That Ruby on Rails doesn't have a simple, global configuration parameter to map
-
to_
in the routing. Or does it?
我最好的解决方案是使用:as
或命名的
The best solution I've is to use :as
or a named route.
我的想法是修改Rails路由以检查该全局配置,并将-
更改为 _
,然后分派给控制器操作。
My idea is to modify the Rails routing to check for that global config and change -
to _
before dispatching to a controller action.
还有更好的方法吗?
推荐答案
在Rails 3和更高版本中,您可以像这样:
With Rails 3 and later you can do like this:
resources :user_bundles, :path => '/user-bundles'
另一种选择是通过初始化程序修改Rails。
但我不建议这样做,因为它可能会在将来的版本中中断(编辑:在Rails 5中不起作用)。
Another option is to modify Rails, via an initializer. I don't recommend this though, since it may break in future versions (edit: doesn't work in Rails 5).
使用<$ c如上所示,最好使用$ c>:path 。
# Using private APIs is not recommended and may break in future Rails versions.
# https://github.com/rails/rails/blob/4-1-stable/actionpack/lib/action_dispatch/routing/mapper.rb#L1012
#
# config/initializers/adjust-route-paths.rb
module ActionDispatch
module Routing
class Mapper
module Resources
class Resource
def path
@path.dasherize
end
end
end
end
end
end
这篇关于在Ruby on Rails中使用破折号`-`而不是下划线`_`进行路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!