Instagramable Walls With Sinatra (Part 2)
A discussion of CRUD
A space to serve as a collection of the world’s greatest walls that are also very instagramable. So far I had accomplished building out the very basics of a MVC design patten, I had a homepage. Now it was time to give some life to my app. In order for my app to flourish I had to give users basic CRUD functionality. In this we also take a peek into the controller which dictates how information is communicated throughout the app.
Controller and CRUD
The acronym CRUD stands for Create, Read, Update, and Delete which are the four major functions implemented in database and applications. This gives the user the ability and logic to create, view, modify and alter data.
Create
class ApplicationController < Sinatra::Base
configure do
enable :sessions
set :session_secret, "secret"
end def current_user
User.find(session[:user_id])
end get '/walls/new' do
@user = current_user
erb :"wall/create_wall"
end post "/walls" do
@wall = Wall.create(location: params[:location],name:
params[:name], user_id: current_user.id)
redirect "/show"
end
end
Read
class ApplicationController < Sinatra::Base
get "/walls/:id" do
@wall = Wall.find_by(id: params[:id])
erb :"wall/show_wall"
end
endUpdate
class ApplicationController < Sinatra::Base
get "/walls/:id/edit" do
@wall = Wall.find_by(id: params[:id])
erb :"wall/edit_wall"
end patch "/walls/:id/edit" do
@wall = Wall.find_by(id: params[:id])
@wall.name = params[:name] if params[:name] != ""
@wall.location = params[:location] if params[:location] != ""
@wall.save
redirect "/show"
end
end
Delete
class ApplicationController < Sinatra::Base
get "/walls/:id/delete" do
@wall = Wall.find_by(id: params[:id])
@wall.destroy
redirect "/show"
end
endThis satisfies our discussion of the controller aspect of our app as well as CRUD. With CRUD, users now have the ability to push content to their hearts content and give the world easier access to the best walls around the globe.