Reputation: 8821
I want to create a web application.
The codes as 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 to use the nesting routes:
resources :users do
resources :articles do
resource :comments do
end
end
But Rails Guide told us to avoid multiple nesting resource. Anyone can give me some good ideas. Thanks in advance!
Upvotes: 0
Views: 57
Reputation: 4577
Yes, you should avoid to nest more that one ressource in another.
You can do this:
resources :users do
resources :articles
end
And this:
resources :articles do
resource :comments
end
So a user has many articles, and articles have many comments.
Upvotes: 0
Reputation: 7034
You can avoid deep nesting using Shallow Nesting
.
resources :users do
resources :articles, shallow: true do
resources :comments
end
end
It will give the same routes as:
resources :users do
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 like this:
users/1
users/1/articles
articles/1
articles/1/edit
articles/1/comments
comments/1
comments/1/edit
You can read more about this here http://guides.rubyonrails.org/routing.html#nested-resources and play with it.
If you want to do it more simple and have urls like this (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 you can do it this way:
resources users do
resources :articles
end
resources articles, only: [] do
resources :comments
end
Good luck and have fun!
Upvotes: 1
Reputation: 1318
Since the relationship between users and articles is not many to many it would be redundant to specify routes for each article and it's comments from the parent.
resources users do
resources :articles
end
resources articles, only: [] do
resources :comments
end
Upvotes: 0