Damir Nurgaliev
Damir Nurgaliev

Reputation: 351

Rails associations routing

I have two models Blog and User with the following association

Blog belongs_to :user

My routes are as follows

resources :users, shallow: true do
  resources :blogs
end

These are the routes generated

   user_blogs GET    /users/:user_id/blogs(.:format)     blogs#index
              POST   /users/:user_id/blogs(.:format)     blogs#create
new_user_blog GET    /users/:user_id/blogs/new(.:format) blogs#new
    edit_blog GET    /blogs/:id/edit(.:format)           blogs#edit
         blog GET    /blogs/:id(.:format)                blogs#show

The question is why some routes ( new_user_blog for example) have the right routing, but others (edit_blog should be edit_user_blog) are wrong?

Upvotes: 0

Views: 114

Answers (1)

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

You are getting these routes because of shallow-nesting

shallow nesting only generates nested routes for index, create and new

As per the documentation using shallow option is equivalent to generate routes as below:

resources :users do
  resources :blogs, only: [:index, :new, :create]
end
resources :blogs, only: [:show, :edit, :update, :destroy]

Which will generate

    user_blogs  GET    /users/:user_id/blogs(.:format)      blogs#index
                POST   /users/:user_id/blogs(.:format)      blogs#create
 new_user_blog  GET    /users/:user_id/blogs/new(.:format)  blogs#new
     edit_blog  GET    /blogs/:id/edit(.:format)            blogs#edit
          blog  GET    /blogs/:id(.:format)                 blogs#show
                PATCH  /blogs/:id(.:format)                 blogs#update
                PUT    /blogs/:id(.:format)                 blogs#update
                DELETE /blogs/:id(.:format)                 blogs#destroy
         users  GET    /users(.:format)                     users#index
                POST   /users(.:format)                     users#create
      new_user  GET    /users/new(.:format)                 users#new
     edit_user  GET    /users/:id/edit(.:format)            users#edit
          user  GET    /users/:id(.:format)                 users#show
                PATCH  /users/:id(.:format)                 users#update
                PUT    /users/:id(.:format)                 users#update
                DELETE /users/:id(.:format)                 users#destroy

whereas using shallow option generates exact same routes as above

Upvotes: 2

Related Questions