2

如果我希望用户网址看起来像

http://site.com/foobar 

代替

http://site.com/users/foobar

foobar将是nickname用户模型中列中用户的昵称。如何防止用户注册顶级路由?比如联系、关于、注销等?

我可以有一个保留名称表。所以当用户注册一个昵称时,它会检查这个表。但是有没有更方便的方法?

4

1 回答 1

1
if(Rails.application.routes.recognize_path('nickname') rescue nil)
  # forbid using desired nickname
else
  # nickname can be used -- no collisions with existing paths
end

升级版:

如果似乎有任何路径被 识别,recognize_path那么你会得到类似的东西:

get ':nick' => 'user#show'

在你的最后,routes.rb这会导致任何路径都可以路由的情况。要解决此问题,您必须使用约束。我给你看一个例子:

# in routes.rb
class NickMustExistConstraint
    def self.matches?(req)
        req.original_url =~ %r[//.*?/(.*)] # finds jdoe in http://site.com/jdoe. You have to look at this regexp, but you got the idea.
        User.find_by_nick $1
    end
end
get ':nick' => 'users#show', constraints: NickMustExistConstraint

通过这种方式,我们将一些动态添加到我们的路由系统中,如果我们有一个带有 nick 的用户,jdoe那么路由/jdoe将被识别。如果我们没有 nick 的用户,那么rroepath/rroe将无法路由。

如果我是你,我只会做两件事:

# in User.rb
def to_param
  nick
end
# in routing.rb
resources :users, path: 'u'

它将使我能够获得类似 a 的路径/u/jdoe(这非常简单并且完全符合 REST)。

在这种情况下,请确保您正在搜索您的用户User.find_by_nick! params[:id](是的,它仍然params[:id]包含一个标题,不幸的是)。

于 2012-04-12T19:26:54.940 回答