繁体   English   中英

Rails为用户嵌套带有漂亮URL的资源

[英]Rails nested resources with pretty URLs for users

我的应用程序的数据结构为:

  • 组织有用户
  • 组织有消息
  • 组织有站点

我通常会使用嵌套资源来RESTful地做到这一点:

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM