2013-04-24 102 views
0

我的應用程序中的數據相當的URL的結構爲:Rails的嵌套的資源,爲用戶

  • 組織有用戶
  • 組織有消息
  • 組織有網站

我通常會使用嵌套資源來做到這一點RESTfully:

resources :organizations do 
    resources :users 
    resources :messages 
    resources :sites 
end 

這給了我喜歡的網址:

/organizations/12/messages 
/organizations/12/sites 

這些羅嗦網址,非常適合當管理員需要爲組織創造一個消息,因爲URL包含組織ID。

然而,我想展現普通用戶相當的URL,例如:

/messages 
/sites 

有沒有辦法別名這些簡潔的URL與/organizations/{current_user.organization.id}/*?

+0

你是什麼意思由/organizations/{current_user.organization.id}/*? – 2013-04-24 13:34:47

+0

你的意思是你想讓你的管理員用戶可以看到他們是很多組織,普通用戶看不到它? – Awea 2013-04-24 13:41:10

+0

@Awea:是的 - 我希望管理員能夠爲所有組織添加消息和更改網站,因此在這種情況下較長的網址很有用。 – Brian 2013-04-24 14:04:37

回答

0

您需要一種方法來傳遞組織標識。 舉例來說,如果你有誰屬於組織和用戶已登錄用戶, 您可以通過CURRENT_USER獲得組織ID如下:

class MessageController < ApplicationController 
before_filter :get_organization 
# ... 
private 
    def get_organization 
    @organization = current_user.organization 
    end 
end 

而且,在你的路線,你可以添加:

resources :messages 
resources :organizations do 
    resources :messages 
end 

還有其他解決方案,但它取決於如何獲得組織ID。