I’m new to RESTful design and confused: if I make PUT, GET or POST to a same resource, say, /weblogs/myweblog, how should I write in the route.rb, and related controller?
Does the following works?
In route.rb
match 'weblogs/myweblog/new' => 'weblogs#create_new_blog'
match 'weblogs/myweblog/edit/:id' => 'weblogs#edit_blog'
.
.
In weblogs_controller.rb
def create_new_blog
...
end
def edit_blog
params[:id]..
....
end
and confused if I want to do GET/PUT/POST on the same resource, if their URL is same but only HTTP request is different, how to write different operations in the controller?
In general it’s best to define your routes in terms of resources, so if you have a resource named
webblog, your routes can be defined using just:If you check the routes generated by this (with
rake routes), you will see that it defines a standard set of mappings fromGET,PUT,POSTandDELETEactions on urls to controller actions:These routes will map to standard controller actions
index,create,new,show, etc.If for whatever reason you want to define routes without using
resources, you can define them separately:By defining routes with
get,putetc. you can map a single URL to multiple controller actions, e.g. like this:This will map the URL /weblogs/myweblog to the method
show_myweblogfor a GET request,update_myweblogfor a PUT request,create_myweblogfor a POST request, anddestroy_myweblogfor a DELETE request.Alternatively, using the standard
resources, you can pick and choose which routes you want from the full set with theonlyoption:See the documentation for more details. I hope this answers your question, if not please provide more details on what you want to do in the comments.