Routing nested resources in Rails 3 Routing nested resources in Rails 3 ruby ruby

Routing nested resources in Rails 3


Have you considered using a shallow nested route in this case?

Shallow Route NestingAt times, nested resources can produce cumbersome URLs. A solution to thisis to use shallow route nesting:

resources :products, :shallow => true do  resources :reviewsend

This will enable the recognition of the following routes:

/products/1 => product_path(1)/products/1/reviews => product_reviews_index_path(1)/reviews/2 => reviews_path(2)


The best way to do this depends on the application, but in my case it is certainly Option B. Using namespaced routes I'm able to use a module to keep different concerns separated out into different controllers in a very clean way. I'm also using a namespace-specific controller to add shared functionality to all controllers in a particular namespace (adding, for example, a before_filter to check for authentication and permission for all resources in the namespace).


I did something similar to this in one of my apps. You're on the right track. What I did was declare nested resources, and build the query using the flexible arel-based syntax of Active Record in Rails 3. In your case it might look something like this:

# config/routes.rbresources :photos, :only => :indexresources :users do  resources :photosend# app/controllers/photos_controller.rbdef index  @photos = Photo.scoped  @photos = @photos.by_user(params[:user_id]) if params[:user_id]  # ...end