在Ruby on Rails中使用破折号`-`而不是下划线`_`进行路由 [英] Routes with Dash `-` Instead of Underscore `_` in Ruby on Rails

查看:76
本文介绍了在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.

我对两件事感到惊讶:


  1. Google等。继续区分它们。

  2. Ruby on Rails没有一个简单的全局配置参数来将-映射到 _ 在路由中。还是呢?

  1. Google et al. continue to distinguish them.
  2. 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屋!

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