Designing Ruby On Rails 4 Routes

时间:2015-10-06 08:48:38

标签: ruby-on-rails ruby routing

I want to achieve something like this: /users/14/images/88 when developing my Rails application. There I have users URL-segment, then comes user ID, and images that belong to this user, and image ID.

I'm asking you, SO, what is the best way to design my routes? Should I keep this pattern or not? I've read this on Ruby On Rails Routing Docs:

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

And this is what confuses me. Not more that 1 level deep.

So, basically, this could mean that one level could be /users/14, but I need one more level (+ /images/88). And according to best practice in designing routes this is bad idea to make more-than-one-level-nested resources. I'm confused a bit about that.

Thanks in advance!

1 个答案:

答案 0 :(得分:4)

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

This is one level deep.


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

This is more than one level deep.


As you can see by the quoted resource, the issue is not about inability to match the resource, but in handling the flow. For example...

#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

Whilst not completely out of range, it shows how confusing deep linking resources can get. You're better advocating a more streamlined approach - for example, appending comments to images & showing them through the images#show controller action.