how to design routes for nesting resources in rails? -


i want create web application.

  1. one user has many articles;
  2. one article has many comments;

the codes below:

class user   .....   has_many :articles end  class article  ....  belongs_to :user  embeds_many :comments end  class comment   ....   embedded_in :article, inverse_of: :comments end 

i want use nesting routes:

resources :users   resources :articles     resource :comments   end end 

but rails guide told avoid multiple nesting resource. can give me ideas. in advance!

you can avoid deep nesting using shallow nesting.

resources :users   resources :articles, shallow: true     resources :comments   end end 

it give same routes as:

resources :users   resources :articles, only: [:index, :new, :create] end  resources :articles, only: [:show, :edit, :update, :destroy]   resource :comments, only: [:index, :new, :create] end  resource :comments, only: [:show, :edit, :update, :destroy] 

and urls this:

users/1 users/1/articles articles/1 articles/1/edit articles/1/comments comments/1 comments/1/edit 

you can read more here http://guides.rubyonrails.org/routing.html#nested-resources , play it.

if want more simple , have urls (deeper nesting):

users/1 users/1/articles/1 users/1/articles/1/edit articles/1/comments articles/1/comments/1 articles/1/comments/1/edit 

then can way:

resources users   resources :articles end  resources articles, only: []   resources :comments end 

good luck , have fun!


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -