How to keep it CRUD and RESTFull in rails (concrete example)

不羁岁月 提交于 2020-01-06 05:40:07

问题


I've difficulties with keeping my controllers not too complicated and with the basic actions rails creates when we scaffold.

Could someone tell me if the approach below is the right one.

I've a model Project and those basic routes it:

GET   /projects            ->   Project#index
GET   /projects/new        ->   Project#new
POST  /projects            ->   Project#create
GET   /projects/:id        ->   Project#show
GET   /projects/:id/edit   ->   Project#edit
PATCH /projects/:id        ->   Project#update
PUT   /projects/:id        ->   Project#update

Now I would like to allow the user to accept the project. First he has a summary view where he can push a button and it should change some value in the model.

My first attempt was

GET   /projects/:id/accept ->   Project#accept
POST  /projects/:id/accept ->   Project#accept_update

This just doesn't feel right.

So I 'm wondering if I should do it in this way:

GET   /projects/:id/accept ->   Acceptations#new
POST  /projects/:id/accept ->   Acceptations#create

But then, I've my Acceptations controller that is dealing with Project models. What starts being confusing for me.

On top of that, if I go with the second options, should the path be /projects/:id/acceptations/new this seems long and confusing for the end user.


回答1:


There is a convention (sometimes known as "heroku REST style") to put these "extra" methods as "actions" under the main resource.

So you'd have this for accepting the project.

 POST /projects/:id/actions/accept

What this route resolves to doesn't matter from the REST viewpoint. Could be an action in ProjectsController. I would likely create a dedicated controller just for this action, controllers/projects/actions/accept_controller.rb

As for the new route, you don't need it for json api. And in case of a GUI (such as your website), you maybe don't need a separate page as well. Instead, it'd just be a small form with "accept" button somewhere on project show page.



来源:https://stackoverflow.com/questions/49127764/how-to-keep-it-crud-and-restfull-in-rails-concrete-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!