Rails 中的多资源路由

发布于 2024-12-27 15:03:53 字数 350 浏览 3 评论 0原文

我有两个不相关的模型,例如 PersonBuilding。当应用程序收到像 www.mysite.com/JohnDoe/EmpireState 这样的 url 时,我想显示名为 johnDoe 的人员的属性,以及名为 EmpireState 的建筑物的属性。

我对路由部分特别感到困惑。我不确定是否需要创建一个可以从数据库返回对象的页面控制器。我该怎么做呢?

我希望有像下面这样的东西吗?

match ':user_name/:building_name', :controller => pages 

I have two unrelated models, say Person and Building. When the app receives a url like www.mysite.com/JohnDoe/EmpireState I would like to show properties of the Person with the name johnDoe, and the same for the building with the name EmpireState.

I'm confused as to the routing part specifically. I'm unsure if I need to create a pages controller that can return the objects from the database. How should I go about doing this?

Am hoping for something like below?

match ':user_name/:building_name', :controller => pages 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

分分钟 2025-01-03 15:03:53

如果这两者没有关系,你就不应该这样做。如果它们相关,我们称之为嵌套资源。

示例:

resources :projecs do
  resources :tasks
end

示例 URL:“/projects/12/tasks/1281”

编辑:
如果它们不相关(取自我的评论):

在您的 BuildingsController 中,您也可以获取父级信息。如果您在问题中使用匹配路线,您将拥有 params[:user_name] 和 params[:building_name] 可用,并且可以使用它们获取您想要的任何内容...

Building.find_by_name(params[:building_name]) # return all Buildings based on URL param

If those two are not related, you shouldn't do it that way. If they ARE related, we call that nested resources.

Example:

resources :projecs do
  resources :tasks
end

Sample URL: "/projects/12/tasks/1281"

Edit:
If they are NOT related (taken from my comment):

In your BuildingsController you can fetch the parent informations too. If you use the match route in your question, you'll have params[:user_name] AND params[:building_name] available and can fetch anything you want with them...

Building.find_by_name(params[:building_name]) # return all Buildings based on URL param
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文