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?