1

在 Rails 3 中,我希望创建一个如下所示的 URL 结构:

http://example.org/learn/cooking/cooking-101/can-anybody-cook

并且对应于以下控制器:

http://example.org/learn/subject/module/lesson

关联将如下所示:

Subject has many Modules
Module belongs to Subject

Module has many Lessons
Lessons belongs to Module

Learn 只是一个集线器或仪表板,将列出所有主题。不会有与其他控制器的关联。

我知道在RailsGuides中,他们警告不要像这样制作多个嵌套资源:

resources :subjects do
  resources :modules do
    resources :lessons
  end
end

这就是我所知道的一切。我有点卡住了。有人可以帮我路由吗?

4

2 回答 2

0

在这种情况下,我认为您应该使用路由命名空间friendly_id gem 并指定自定义路径。像下面这样的东西应该会有所帮助:

namespace :learn do
  resources :subjects, path: '' do
    resources :modules, path: '' do
      resources :lessons
    end
  end
end

有关安装的更多信息,friendly_id请阅读rails quick-start。您应该在您的类 ( , , )中添加slug列和扩展friendly_id模块。另见railscastSubjectModuleLesson

于 2013-01-17T08:42:32.820 回答
0

我要解决的方法是为每个主题、模块和课程创建自定义显示路线,而不是嵌套资源,我认为在这种情况下没有必要。

所以我将每个资源设置如下:

resources :subjects, :except => [:show]
resources :modules, :except => [:show]
resources :lessons, :except => [:show]

然后明确匹配显示路由:

match '/learn/:subject/:module/:lesson' => 'lessons#show', :as => 'show_lesson'
match '/learn/:subject/:module' => 'modules#show', :as => 'show_module'
match '/learn/:subject' => 'subjects#show', :as => 'show_subjects'

这将使您在定义 show 路由时更加精细(这是您要为其自定义 url 的正常操作)。

现在根据您的要求,您可能仍希望嵌套资源,但希望这能给您一些想法。

顺便说一下,我用 show_ 命名我的 show_xxx 路由只是为了澄清它们是命名路由,并避免任何可能的冲突,以防我决定在资源上使用 show。

于 2013-01-17T04:38:25.543 回答