问题描述
我希望我的网址使用破折号 -
而不是下划线 _
作为单词分隔符.例如 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).
如上所示使用 :path
更好.
Using :path
as shown above is better.
# 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 中使用破折号 `-` 而不是下划线 `_` 的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!