缩短 Rails 条路线

Shortening Rails Routes

我怎样才能在我的 rails 申请中缩短这些极其冗长的路线?

# routes.rb

  resources :courses do
    resources :sections do
      resources :lessons do
        resources :sub_lessons
      end  
    end
  end 

我推荐关注railsoficial guides。避免嵌套资源深度超过 1 层被认为是一种很好的做法。也就是说,如果您确实需要这种嵌套级别,您可以使用 shallow 选项。这样至少你的路线会更干净。如上面引用的文档中所述:

One way to avoid deep nesting (as recommended above) is to generate the collection actions scoped under the parent, so as to get a sense of the hierarchy, but to not nest the member actions. In other words, to only build routes with the minimal amount of information to uniquely identify the resource

您可以尝试这样的操作:

resources :courses, shallow: true do
  resources :sections, shallow: true do
    resources :lessons, shallow: true do
      resources :sub_lessons
    end  
  end
end

稍微尝试一下,然后使用 rake routes 查看您的路线。

但是,您应该问问自己,例如,我是否需要将课程安排在各个部分下?拆分它们可能更好,例如:

resources :courses do
  resources :sections
end

resources :lessons do
  resources :sub_lessons
end  

这完全取决于您在什么操作中需要的范围,例如,如果在某些操作中您需要根据课程而不是部分来限制课程,那么您只需要将课程 ID 作为参数传递。