路由使用Dash`-`而不是Ruby on Rails中的Underscore`_`

时间:2011-03-17 03:09:20

标签: ruby-on-rails routing rails-routing

我希望我的网址使用短划线-代替下划线_作为单词分隔符。例如controller/my-action而不是controller/my_action

我对两件事感到惊讶:

  1. Google et al。继续区分他们。
  2. Ruby on Rails没有简单的全局配置参数来在路由中将-映射到_。或者是吗?
  3. 我最好的解决方案是使用:as或命名路线。

    我的想法是修改Rails路由以检查该全局配置,并在分派到控制器操作之前将-更改为_

    有更好的方法吗?

4 个答案:

答案 0 :(得分:64)

使用Rails 3及更高版本,你可以这样做:

resources :user_bundles, :path => '/user-bundles'

另一种选择是通过初始化程序修改Rails。 我不建议这样做,因为它可能会在将来的版本中破坏。

如上所示使用: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

答案 1 :(得分:2)

您可以使用命名路由。它允许使用' - '作为单词分隔符。在routes.rb中,

map.name_of_route     'a-b-c',       :controller => 'my_controller', :action => "my_action"

现在,像http://my_application/a-b-c这样的网址会转到指定的控制器和操作。

另外,用于创建动态网址

map.name_of_route    'id1-:id2-:id3',       :controller => 'my_controller', :action => "my_action"

在这种情况下'id1,id2& id2将作为http参数传递给动作

在你的行动和观点中,

name_of_route_url(:id1=>val1, :id2=>val2, :id3=>val3) 

会评估为网址“http://my_application/val1-val2-val3”。

答案 2 :(得分:2)

如果您在控制器和视图文件中使用下划线,那么只需在路径文件中使用短划线,它就可以工作..

获取'blog / example-text'这是我对此控制器的路线

def example_text 结束< - 这是我的控制器

和example_text.html.erb是文件

这是实际链接site.com/blog/example-text

我认为这对我有用,而且比强调SEO明智更有效

答案 3 :(得分:2)

您可以重载控制器和操作名称以使用破折号:

# config/routes.rb
resources :my_resources, path: 'my-resources' do
  collection do
    get 'my-method', to: :my_method
  end
end

您可以在控制台中进行测试:

rails routes -g my_resources
my_method_my_resources GET  /my-resources/my-method(.:format) my_resources#my_method