在Rails的URL中给用户名添加符号前缀

时间:2019-07-17 12:43:55

标签: ruby-on-rails ruby

我正在我的应用程序中实现用户名系统,并且试图使URL美观。我宁愿没有这样的东西:

myapp.com/users/joebloggs

myapp.com/u/joebloggs

但是

myapp.com/joebloggs

如果我想要漂亮的版本,我将必须将全部路径列入白名单,而我不希望这样做。我注意到Medium.com和producthunt.com采取了以下措施来解决此问题:

myapp.com/@joebloggs

如何在用@符号作为用户名前缀的Rails 6应用中创建相同的内容?非常确定我必须为路由命名空间,但是不确定如何准确实现它。我认为类似以下内容的方法可能有效,但无效。

switch (i) {
   case 6: ...
   case 7: ...
   case 12: ...
}
if (i >= 13 && i % 3 == 1) { // 13, 16, 19...
   tokenval = scripBO.setTokenNumber(Long.parseLong(parameter));
}

1 个答案:

答案 0 :(得分:2)

只需在路由前面加上@符号,然后在其后加上您要捕获的变量名称即可,例如:

# config/routes.rb
get '@:user_id' => 'users#show'

,然后在您的控制器中,仅引用变量名称,如下所示:

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def show
    render json: { user_id: params[:user_id] }.to_json
  end
end

这是您将得到的:

// http://localhost:3000/@joe

{
  "user_id": "joe"
}

编辑:如果您想为该特定@user的页面设置范围,也可以使用相同的方法进行操作:

  # config/routes.rb

  scope '@:user_id' do
    get 'scoped', to: 'users#scoped'
  end
http://localhost:3000/@joe/scoped