4

I know how to setup nested resources in the routes files already… the question is for how to do it optionally with the same payload, and with fewer lines.

Lets say I have a BlogSite. BlogSite has many Posts, but it also has many Authors and many Dates. (this might not be the best example, but bear with me).

To do CRUD on a Post, I want to be able to use

/blog_sites/1/author/2/date/3/posts #all posts on site 1 from author 2 on date 3
/blog_sites/1/author/2/posts        #all posts on site 1 from author 2
/blog_sites/1/date/3/posts          #all posts on site 1 on date 3
/blog_sites/1/posts                 #all posts on site 1
/author/2/date/3/posts              #all posts from author 2 on date 3
/author/2/posts                     #all posts from author 2
/date/3/posts                       #all posts from date 3
/posts                              #all posts 

Such that any of the filtering parameters can be optional in the URL. I know that you can use something like

get (/blog_sites/:blog_id)(/author/:author_id)(/date/:date_id)/posts => "posts#index"

but I don't want to lose all the CRUD benefits of using nested resource routing. Currently I have to duplicate much of the routing to make it work, and am looking for a better way to do this:

resources :blog_sites do
    resources :authors do
        resources :dates do
            resources :posts
        end
        resources :posts
    end
    resources :dates do
        resources :posts
    end
    resources :posts
end

… and so on. It can get pretty unmanageable petty quickly.

How can I maintain the optional param urls whilst keeping routes.rb DRY and sane?

coneybeare
  • 33,113
  • 21
  • 131
  • 183

1 Answers1

4

Try to use scope and resources together. Rails 3 routing with resources under an optional scope

scope 'blog_sites/:blog_id)(/author/:author_id)(/date/:date_id)' do 
    resources :posts
end
Community
  • 1
  • 1
gayavat
  • 18,910
  • 11
  • 45
  • 55
  • This was exactly how I ended up solving it, though I used nested scopes so I could specify the conditions all of the params cleanly on each line, next to its resource – coneybeare Mar 13 '12 at 12:32