2012-06-15 95 views
2

我想在路徑中使用UUID id標準ID。這個工程:Rails 3與約束條件的嵌套路由

# 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"

我缺少什麼?

Thx提前。

筆記:我在軌道3.2.2和紅寶石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}/} 

回答

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應用程序中測試過。

+0

謝謝你,約翰,你說得對,是這樣工作的。我的理解是一樣的 - 差不多。我相信,在嵌套的情況下父親約束被設置爲父親ID(唯一):所以我認爲你的設置會採取/職位/ [適當的uuid] /評論/:ID(在我的例子中爲摧毀),而是的意向/帖子/ [適當的uuid] /評論/ [適當的uuid]格式。它對我有意義,但我錯了。我無法在文檔中找到任何對嵌套情況的引用,順便說一句。 – fastcatch

+0

是的,我從來沒有在文檔中看到過,這是一個恥辱。當別人遇到同樣的問題並正在嘗試時,我只會遇到它。 – JohnMetta

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}/

+0

你說得對,的確如此。 (在我的情況下,我生成的UUID全部小寫,並且任何人都不可能編輯它們。但是,您的評論完全有效並且很有用。) BTW:這個怎麼樣:)? ''UUID_regex =/[0-9a-fA-F] {8}( - [0-9a-fA-F] {4}){3} - [0-9a-fA-F] {12} /更準確地說:我的UUID總是4級的,所以也可以檢查。 (儘管如此,我會把它留給讀者:)) – fastcatch