在 Rails 4 条路线上设计 Ruby

Designing Ruby On Rails 4 Routes

我想实现这样的目标:/users/14/images/88 在开发我的 Rails 应用程序时。 我有用户 URL 段,然后是用户 ID、属于该用户的图像和图像 ID。

我问你,设计路线的最佳方式是什么?我应该保留这种模式吗? 我在 Ruby 上读过这个在 Rails 路由文档:

[ ! ] Resources should never be nested more than 1 level deep.

这就是让我困惑的地方。深度不超过 1 层。

所以,基本上,这可能意味着一级可以是 /users/14,但我还需要一级 (+ /images/88)。根据设计路线的最佳实践,制作多级嵌套资源是个坏主意。 我对此有点困惑。

提前致谢!

#config/routes.rb
resources :users do
   resources :images
end

这是一层深。


#config/routes.rb
resources :users do
   resources :images do
      resources :comments
   end
end

这不止一层。


正如您在quoted resource中看到的,问题不在于无法匹配资源,而是在于处理流程。例如...

#app/controllers/comments_controller.rb
class CommentsController < ApplicationController
   def show
      @user = User.find params[:user_id]
      @image = @user.images.find params[:image_id]
      @comments = @image.comments
   end
end

虽然没有完全超出范围,但它显示了深层链接资源会变得多么混乱。您最好提倡一种更精简的方法 - 例如,将 comments 附加到 images 并通过 images#show 控制器操作显示它们。