The resources method is a method that collectively sets the routing for the seven basic actions. Yeah I know that. But what is resource ... Did you forget to add "s"? So, today I will summarize the singular resource resource.
It looks like it has an s, but it works quite differently.
Consider a system with administrative and general users. After logging in, general users can only view and manage their own accounts. In this case, if you set the route in resources, the setting will be done as follows.
resources :users
HTTP | path | controller#action |
---|---|---|
GET | /users | users#index |
GET | /users/new | users#new |
POST | /users | users#create |
GET | /users/:id | users#show |
GET | /users/:id/edit | users#edit |
PATCH/PUT | /uses/:id | users#update |
DELETE | /users/:id | users#destroy |
As I said earlier, users can only view and manage their own accounts. If you can only see your account, you can see that you don't need the index action to list users.
The first thing that comes out is only, except, and you only have to remove the index. That's right. Is that all okay? Let's check the route again.
HTTP | path | controller#action |
---|---|---|
GET | /users/:id | users#show |
GET | /users/:id/edit | users#edit |
PATCH/PUT | /uses/:id | users#update |
DELETE | /users/:id | users#destroy |
What you should consider here is the: id of the path. Users can view and manage their accounts when they are logged in. If you are logged in, you can get the user's id attribute from the user's session object. ⇨ There is no need to put the id parameter in the URL path! !! You can see that.
In other words, the path you should aim for is the one without the: id from the table above.
** Here comes the resource when it's full **
By using a single resource here, we have realized routing that meets the above needs! !!
resource :user
HTTP | path | controller#action |
---|---|---|
GET | /user/new | users#new |
POST | /user | users#create |
GET | /user | users#show |
GET | /user/edit | users#edit |
PATCH/PUT | /user | users#update |
DELETE | /user | users#destroy |
As above: Use the resource method for routing without id and index actions You can set it. I learned one more thing.
Today's article is over.
It was the 11th day of the series of engineers who became full-fledged 100 days later.
89 days to become a full-fledged engineer
Recommended Posts