Rails - redundant RESTful Actions for map.resources? (new, create)

I was wondering why when you create calm routes in rails with map.resources it generates actions for new, create, edit, update ? Is there something wrong with declaring only one action for create and update and doing something like this?

def create
  unless post?
     @user = User.new
  else
     redirect_to :action => 'index' if user.create(params[:user])
  end
end

      

so that we can have something like

:GET  users/create # to show the form (same as action - new)
:POST users/create # to create a new user

      

since Restful is verb based, wouldn't that be the best approach to use?

Thank you for your attention.

+2


source to share


1 answer


I think there are two related but different problems here: the public urls and the controller methods they are directed to. Since any of them can be changed independently, I will refer to them separately. Also, note that I will be talking a little fluently and strictly about REST as implemented in the Rails context.

With regard to external URLs, I think it helps distinguish between URLs that make up the system API ( :GET users/1

, :PUT users/1

etc.) and URLs that are just accessible for human convenience using a web browser ( users/new

,users/5/edit

etc.). An API is about selecting resources or interacting with them in some way - these are URLs that another computer will use when interacting with your system. These urls are usually just the address of the resource you want to interact with and then use the HTTP method and parameters to specify what you want to do (GET = show me this resource, PUT = change this resource, etc.) ... Friendly URLs for displaying a form to facilitate human use of the API. You can edit the user using curl to manually print all the options you wanted to change and do a POST to users / 1, but as a human it is much easier if you can just use the form.



To look at your examples above, then it :GET users/create

might make sense (and is very similar :GET users/new

to the default), but :POST users/create

would roughly translate to "create new user / create" which is not entirely clear.

Regarding controller methods, "new" and "created" perform fundamentally different tasks, hopefully from the previous paragraphs. One of them renders the form and the other creates a new resource. You can of course overload the same method, but for no good reason, creating two small independent methods to handle two small independent problems is probably a more natural approach.

+4


source







All Articles