Rails 3具有约束的嵌套路由

时间:2012-06-15 19:50:19

标签: ruby-on-rails-3 routes

我想在路由中使用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}/}

2 个答案:

答案 0 :(得分: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应用程序中进行测试。

答案 1 :(得分:1)

UUID使用十六进制数字,因此应将a-z收紧到a-f。此外,十六进制不区分大小写,因此'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}/