Skip to content

Instantly share code, notes, and snippets.

@ltw
Last active October 27, 2015 03:33
Show Gist options
  • Select an option

  • Save ltw/4cacae039d4cecab6365 to your computer and use it in GitHub Desktop.

Select an option

Save ltw/4cacae039d4cecab6365 to your computer and use it in GitHub Desktop.
Let's talk about REST, shall we?

REST Routing

So here's one way to think about routes:

-- retrieving data about a contact or contacts
# index   GET /contacts         Contact.all
# show    GET /contacts/1       Contact.find(1)

-- helping you create a new contact
# new     GET /contacts/new     Contact.new
# create  POST /contacts        Contact.create(...)

-- helping you update a single contact
# edit    GET /contacts/1/edit  Contact.find(1).name=
# update  PUT /contacts/1       Contact.find(1).update_attributes(name: 'The man', street: 'Best St.')

-- destroy a contact
# destroy DELETE /contacts/1    Contact.find(1).destroy

Another way of thinking about this is which routes deal with the collection of objects and which routes deal with a single member of the collection of objects:

# -- collection routes
# index   GET /contacts
# new     GET /contacts/new
# create  POST /contacts

# -- member routes
# show    GET /contacts/1
# edit    GET /contacts/1/edit
# update  PUT /contacts/1
# destroy DELETE /contacts/1

Yet another way to think about this is which routes should redirect and which should render:

-- render
# index   GET /contacts
# new     GET /contacts/new
# edit    GET /contacts/1/edit
# show    GET /contacts/1   Contact.find(1)

-- redirect
# create  POST /contacts     -> index or show
# update  PUT /contacts/1    -> show
# destroy DELETE /contacts/1 -> index
# index
get '/contacts' do
@contacts = Contact.all
erb :"contacts/index"
end
# new
get '/contacts/new' do
@contact = Contact.new
erb :"contacts/new"
end
# show
get '/contacts/:id' do
@contact = Contact.find_by(id: params[:id])
erb :"contacts/show"
end
# edit
get '/contacts/:id/edit' do
@contact = Contact.find_by(id: params[:id])
erb :"contacts/edit"
end
# create
post '/contacts' do
contact = Contact.create(params[:contact])
redirect "/contacts/#{contact.id}"
end
# update
put '/contacts/:id' do
contact = Contact.find_by(id: params[:id])
contact.update_attributes(params[:contact])
redirect "/contacts/#{contact.id}"
end
# destroy
delete '/contacts/:id' do
contact = Contact.find_by(id: params[:id])
contact.destroy
redirect '/contacts'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment