Rails routes, has_many and an additional nested resource?

I know how to already set nested resources in route files ... the question is how to do this, with the same payload and with fewer lines.

Let's say I have BlogSite . BlogSite has many Posts , but it also has many Authors and many Dates . (this may not be the best example, but carry me).

To make CRUD on 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 

Thus, any of the filtering options may be optional in the URL. I know you can use something like

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

but I do not want to lose all the benefits of CRUD using nested resource routing. Currently, I have to duplicate most of the routing to get it working, and I'm 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 become quite uncontrollable shallow quickly.

How can I support optional parameters while keeping .rb DRY and reasonable routes?

+4
source share
1 answer

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

 scope 'blog_sites/:blog_id)(/author/:author_id)(/date/:date_id)' do resources :posts end 
+4
source

Source: https://habr.com/ru/post/1393578/


All Articles