Using Yii2 framework I cannot find any built-in functionality to implement something called nested resources
in Ruby on Rails (http://guides.rubyonrails.org/routing.html#nested-resources)
For example, an Article has many Comments. So I want that comments related to an article will be accessed via /articles/1/comments
URL when index
action is used; via /articles/1/comments/create
when create
action is used and so on...
Do I have to add multiple action-methods to ArticlesController called actionIndexComments(), actionCreateComment()...
?
Or should I pass an ?article_id=1
parameter via GET and use it for filtering in CommentsController ?
Or should I maybe implement custom UrlManager
class that can deal with nested routes? (maybe someone has already implemented it?)
What is the best practice for now?
You should be able to do this easily with the UrlManager. It also depends on where you want to put the actual actions. You can put them either in a article controller or comment controller
For example for the comments controller you can define rules like this:
'article/<article_id:\d+>/comments/create/' => 'comment/create',
'article/<article_id:\d+>/comments/' => 'comment/index',
In both cases you can access the article_id (in GET) in the create or index actions. You can do exactly the same thing if you want to put the actions in the article.
For more universe:
'GET,HEAD v1/articles/<id:\d+>/comments' =>
'v1/articles/comment/index',
'GET,HEAD v1/<article/<id:\d+>/comments/<id:\d+>' =>
'v1/articles/comment/view',
'POST v1/articles/<id:\d+>/comments' =>
'v1/articles/comment/create',
'PUT,PATCH v1/article/<id:\d+>/comments' =>
'v1/articles/comment/update',
'DELETE v1/article/<id:\d+>/comments' =>
'v1/articles/comment/delete',
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With