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

查看:14
本文介绍了在 Ruby on Rails 中使用 Dash `-` 而不是下划线 `_` 的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的网址使用破折号 - 而不是下划线 _ 作为单词分隔符.例如 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. 谷歌等.继续区分它们.
  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).

如上图使用: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 中使用 Dash `-` 而不是下划线 `_` 的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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