2

我想在路由中使用 UUID 代替 id 标准 ID。这有效:

# UUIDs are used for ids
UUID_regex = /([a-z0-9]){8}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){12}/
resources :posts, :only => [:index, :show, :create], :constraints => {:id => UUID_regex}

那就是 Rails 可以接受/posts/fb0f7c67-6f9b-4e2c-a26b-7700bb9b334d

但是,当我开始像这样嵌套它们时,

# UUIDs are used for ids
UUID_regex = /([a-z0-9]){8}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){12}/
resources :posts, :only => [:index, :show, :create], :constraints => {:id => UUID_regex} do
  resources :comments, :only => [:create, :destroy], :constraints => {:id => UUID_regex}
end

Rails 开始抱怨:No route matches [POST] "/post/fb0f7c67-6f9b-4e2c-a26b-7700bb9b334d/comments"

我错过了什么?

提前谢谢。

注意:我在 Rails 3.2.2 和 ruby​​ 1.9.3 上;rake routes是:

post_comments POST   /posts/:post_id/comments(.:format)     comments#create {:id=>/([a-z0-9]){8}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){12}/, :post_id=>/([a-z0-9]){8}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){12}/}
post_comment  DELETE /posts/:post_id/comments/:id(.:format) comments#destroy {:id=>/([a-z0-9]){8}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){12}/, :post_id=>/([a-z0-9]){8}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){12}/}
       posts  GET    /posts(.:format)                       posts#index {:id=>/([a-z0-9]){8}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){12}/}
              POST   /posts(.:format)                       posts#create {:id=>/([a-z0-9]){8}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){12}/}
        post  GET    /posts/:id(.:format)                   posts#show {:id=>/([a-z0-9]){8}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){12}/}
4

2 回答 2

3

据我所知,当您在父路由上设置约束时,子路由将继承该字段上的约束。因此,我的理解是:

UUID_regex = /([a-z0-9]){8}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){4}-([a-z0-9]){12}/
resources :posts, :only => [:index, :show, :create], :constraints => {:id => UUID_regex} do
  resources :comments, :only => [:create, :destroy]
end

足够了。不是这样吗?我的应用程序仍在 3.1/1.9.2 中,因此尚未在 3.2 应用程序中进行测试。

于 2012-06-15T20:39:30.470 回答
1

UUID 使用十六进制数字,因此 az 应紧缩为 af。此外,十六进制不区分大小写,因此“C”和“c”都是有效数字。我使用以下内容:

UUID_regex = /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/

于 2013-11-10T13:02:41.877 回答