没有资源名称的Rails路由 [英] Rails routing without resource name

查看:73
本文介绍了没有资源名称的Rails路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的rails应用程序具有Section模型和Page模型。一个部分有很多页面。

My rails app has a Section model and a Page model. A section has many pages.

# section.rb
class Section < ActiveRecord::Base
    has_many :pages 
end

# page.rb
class Page < ActiveRecord::Base
    belongs_to :section 
end

假设我有一个Section带有子词 about,并且该部分包含三页,其中有子词 intro, people, history,具有典型路由的网址可能看起来像这样:

Assuming I have a Section with slug 'about', and that section has three pages with slugs 'intro', 'people', 'history,' a url with typical routing might look something like this:

http://example.com/sections/about/pages/intro
http://example.com/sections/about/pages/people
http://example.com/sections/about/pages/history

设置的最佳方法是什么设置我的路线,以便可以使用以下网址:

What is the best way to set up my routes so that I can use these urls:

http://example.com/about/intro
http://example.com/about/people
http://example.com/about/history


推荐答案

为了从所有路线中同时删除 section 和<$ c $的 sections和 pages c>页面,您可以使用:

In order to remove "sections" and "pages" from all routes for both sections and pages, you could use:

resources :sections, path: '' do
  resources :pages, path: ''
end

重要提示:请确保将其放在路线页面的底部。例如,您有一个示例控制器,并说您的 routes.rb 如下所示:

Important: be sure to put this to the bottom of your routes page. For instance, it you have an example controller, and say your routes.rb appeared as follows:

resources :sections, path: '' do
  resources :pages, path: ''
end
resources :examples
root 'home#index'

通过上述设置,转到 http://example.com/examples 会将您转到示例 部分,而不是 examples#index ,然后转到 http://example.com/ 会将您发送到 sections#index ,而不是 home#index 。因此,以上配置应如下所示:

With the above setup, going to http://example.com/examples would send you to the "examples" section, rather than than examples#index, and going to http://example.com/ would send you to sections#index rather than home#index. So, the above configuration should look like this:

resources :examples
root 'home#index'
resources :sections, path: '' do
  resources :pages, path: ''
end

这篇关于没有资源名称的Rails路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆