how to design routes for nesting resources in rails? -
i want create web application.
- one user has many articles;
- 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
Post a Comment