Reputation: 2740
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?
Upvotes: 0
Views: 150
Reputation: 27374
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:
resources :weblogs
If you check the routes generated by this (with rake routes
), you will see that it defines a standard set of mappings from GET
, PUT
, POST
and DELETE
actions on urls to controller actions:
webblogs GET /weblogs(.:format) weblogs#index
POST /weblogs(.:format) weblogs#create
new_webblog GET /weblogs/new(.:format) weblogs#new
webblog GET /weblogs/:id(.:format) weblogs#show
PUT /weblogs/:id(.:format) weblogs#update
DELETE /weblogs/:id(.:format) weblogs#destroy
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:
get '/weblogs' => 'weblogs#index'
get '/weblogs/new' => 'weblogs#new'
get '/weblogs/:id/edit' => 'weblogs#edit'
put '/weblogs/:id' => 'weblogs#update'
...
By defining routes with get
, put
etc. you can map a single URL to multiple controller actions, e.g. like this:
get '/weblogs/myweblog' => 'weblogs#show_myweblog'
put '/weblogs/myweblog' => 'weblogs#update_myweblog'
post '/weblogs/myweblog' => 'weblogs#create_myweblog'
destroy '/weblogs/myweblog' => 'weblogs#destroymy_weblog'
This will map the URL /weblogs/myweblog to the method show_myweblog
for a GET request, update_myweblog
for a PUT request, create_myweblog
for a POST request, and destroy_myweblog
for a DELETE request.
Alternatively, using the standard resources
, you can pick and choose which routes you want from the full set with the only
option:
resources :weblogs, only: [:show, :edit]
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.
Upvotes: 1