在 Rails 中的同一路由路径 '/' 上有两个不同的资源

Having two different resources on the same route path '/', in Rails

我的应用程序中有用户和组织。我想让路由功能像 Github 一样,您基本上同时拥有两者:

/john-doe

/约翰组织

解决此问题的最佳方法是什么?

谢谢!

如果您使用 ActiveRecord 进行数据访问并且不介意修改模型,
那么 Polymorphic Associations or Single table inheritance 应该可以工作。

使用单一 table 继承思想,我们的模型可以像这样:

class Resource < ActiveRecord::Base; end
class User < Resource; end
class Organization < Resource; end

我们的 table 如下所示:

+----+----------------+-------------------+--------------------+
| id | Type           | Name              | Slug               |
+----+----------------+-------------------+--------------------+
| 1  | Users          | John Doe          | john-doe           |
| 2  | Organizations  | John Organization | johns-organization |
+----+----------------+-------------------+--------------------+

那么我们应该可以通过

访问资源
resource = Resource.where(slug: 'john-doe').first
resource.type # user or organization
# which you can use to decide how to render the views accordingly.