Created
May 7, 2014 19:24
-
-
Save ndelage/5f3f13cb6b311b76dd10 to your computer and use it in GitHub Desktop.
Restful Routes 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 2 resources: | |
# 1) Sessions | |
# 2) Bands | |
# | |
# 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="/band/<%[email protected]%>" method="post"> | |
# <input type="hidden" name="_method" value="delete"/> | |
# | |
# <input type="submit" value="Delete Band with id: <%[email protected]%>"/> | |
# </form> | |
# Show the login page | |
get "/sessions/new" do | |
erb :"sessions/new" | |
end | |
# Create a new session (log the user in) | |
post "/sessions" do | |
@user = User.find(email: params[:email]) | |
@user.authenticate(params[:password]) | |
session[:user_id] = @user.id | |
redirect "/users/#{@user.id}" | |
end | |
# Delete a session (clear the session cookie) | |
delete "/sessions" do | |
session.clear | |
redirect "/sessions/new" | |
end | |
# Read | |
# | |
# show all bands (index) | |
get "/bands" do | |
@band = Band.all | |
erb :"bands/index" | |
end | |
# show one band by id (show) | |
get "/bands/:id" do | |
@band = Band.find(params[:id]) | |
erb :"bands/show" | |
end | |
# show the form to create a new | |
get "/bands/new" do | |
erb :"bands/new" | |
end | |
# create a new band record (create) | |
post "/bands" do | |
@band = Band.new(params[:band]) | |
if @band.save | |
redirect "/bands" | |
else | |
erb :"bands/new" | |
end | |
end | |
# Update | |
# | |
# show the form to edit a band | |
get "/bands/:id/edit" do | |
@band = Band.find(params[:id]) | |
erb :"/bands/edit" | |
end | |
# update the band by id (update) | |
put "/bands/:id" do | |
@band = Band.find(params[:id]) | |
# params => {id: 3, band: {name: "The Killers", member_count: 4}, _method: "put"} | |
if @band.update(params[:band]) | |
redirect "/bands/#{@band.id}" | |
else | |
erb :"bands/edit" | |
end | |
end | |
# delete a band by id (destroy) | |
delete "/bands/:id" do | |
@band = Band.find(params[:id]) | |
@band.delete | |
redirect "/bands" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment