应用程序的数据结构如下:
- 组织有用户
- 组织有消息
- 组织有网站
我通常会使用嵌套的资源以rest方式完成:
resources :organizations do
resources :users
resources :messages
resources :sites
end
给我这样的url:
/organizations/12/messages
/organizations/12/sites
当管理员需要为组织创建消息时,这些冗长的URL非常适合,因为URL包含组织ID。
然而,我想向普通用户展示漂亮的url,如:
/messages
/sites
是否有办法别名这些漂亮的url到/organizations/{current_user.organization.id}/* ?
需要一种传递组织id的方法。例如,如果您有一个属于某个组织的用户,并且该用户已登录,您可以通过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。