【问题标题】:Custom routes in railsRails 中的自定义路线
【发布时间】:2026-01-28 15:25:01
【问题描述】:

我有一个用户控制器。

对于特定用户,我想要这样的东西

 example.com/a_constant_string ==> example.com/users/2

我只需要特定用户,而不是所有用户。你可以说

link_to 'Go to a specific user', @user
link_to 'Go to a specific user', user_path(@user)
link_to 'Go to a specific user', a_constant_string_path

应该是一样的。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 routes custom-routes


    【解决方案1】:

    这也可以:

    match '/a_constant_string', {controller: 'users', id: 2}
    

    具有不发送浏览器重定向的额外好处 (IMO)。

    【讨论】:

      【解决方案2】:

      您可以在 config/routes.rb 中创建重定向路由:

      match '/a_constant_string', :to => redirect("/users/2")
      

      这将重定向到正确的路径,并为您提供 URL 和 PATH 助手:a_constant_string_patha_constant_string_url

      【讨论】: