Created
June 3, 2014 20:55
-
-
Save ndelage/8e41a1aab180a755dd69 to your computer and use it in GitHub Desktop.
Restful Orders Routing example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
## RESTful routes for an 'orders' resource | |
# | |
# Note: In order to use the 'other' HTTP verbs (put & delete) you need to enable the | |
# method_override feature of Sinatra. | |
# | |
# (in config/environment.rb) | |
# config do | |
# set :method_override, true | |
# | |
# end | |
# | |
# Don't forget to include the hidden _method input on forms | |
# you want to use a non-get/post http verb. e.g. | |
# | |
# <form action="/orders/<%[email protected]%>" method="post"> | |
# <input type="hidden" name="_method" value="delete"/> | |
# | |
# <input type="submit" value="Delete Order with id: <%[email protected]%>"/> | |
# </form> | |
## | |
## Read | |
## | |
# show an order, by a particular id | |
get "/orders/:id" do | |
@order = Order.find(params[:id]) | |
erb :"orders/show" | |
end | |
# show all orders | |
get "/orders" do | |
@orders = Order.all | |
erb :"orders/index" | |
end | |
## | |
## Create | |
## | |
# show the new order form | |
get "/orders/new" do | |
@order = Order.new | |
erb :"orders/new" | |
end | |
# receive data from the new order form & create the order | |
post "/orders" do | |
@order = Order.new(params[:order]) | |
if @order.save | |
redirect "/orders" | |
else | |
erb :"orders/new" | |
end | |
end | |
## | |
## Update | |
## | |
# show the edit form | |
get "/orders/:id/edit" do | |
@order = Order.find(params[:id]) | |
erb :"orders/edit" | |
end | |
# receive data from the edit form and update the order | |
put "/orders/:id" do | |
@order = Order.find(params[:id]) | |
if @order.update(params[:order]) | |
redirect "/orders/#{@order.id}" | |
else | |
erb :"orders/edit" | |
end | |
end | |
## | |
## Delete | |
## | |
delete "/orders/:id" do | |
@order = Order.find(params[:id]) | |
@order.delete | |
redirect "/orders" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment