Skip to content

Instantly share code, notes, and snippets.

@marcoranieri
Created July 29, 2019 17:36
Show Gist options
  • Save marcoranieri/efd5944ffdfe5ddf58095696df3207a8 to your computer and use it in GitHub Desktop.
Save marcoranieri/efd5944ffdfe5ddf58095696df3207a8 to your computer and use it in GitHub Desktop.
SINATRA Framework
# C O N T R O L L E R
require_relative "config/application"
require "sinatra"
require "sinatra/reloader"
require "sinatra/activerecord"
require "pry"
# As a user I can list all the restaurants ( INDEX Action )
get "/" do
@restaurants = Restaurant.all.reverse
erb :index
end
# As a user I can see one restaurant's details ( SHOW Action )
# restaurants/3 <- we want to make this id dynamic!!
# Using PARAMS I can fetch user inputs in the URL
get "/restaurants/:id" do
id = params["id"].to_i
@restaurant = Restaurant.find(id)
erb :show
end
# As a user I can add a restaurant ( CREATE Action )
# Using PARAMS I can fetch user inputs in the URL ( after a POST request )
post "/restaurants" do
name = params["name"]
city = params["city"]
rest = Restaurant.new(name: name, city: city)
rest.save
# redirect "/restaurants/#{rest.id}"
redirect "/"
end
# view/index.erb
# we can use @restaurants from the controller ( app.rb )
<h1>List of my fav restaurants</h1>
<h3>Add a NEW restaurant:</h3>
<form action="/restaurants" method="post">
<label for="name">Name</label>
<input type="text" name="name">
<label for="city">City</label>
<input type="text" name="city">
<input type="submit">
</form>
<ul>
<% @restaurants.each do |restaurant| %>
<li>
<a href="restaurants/<%= restaurant.id %>">
<%= restaurant.name %>
</a>
</li>
<% end %>
</ul>
# models/restaurant.rb
class Restaurant < ActiveRecord::Base
end
# SHORTCUTS for erb -> embedded ruby ( IN HTML Page )
# To run ruby in erb file : <% %> & <%= %>
# pe + TAB -> <%= %> ( display the output in the browser ) <%= Time.now %>
# er + TAB -> <% %> ( runs the ruby command in the background ) <% now = Time.now %>
# view/show.erb
# we can use @restaurant from the controller ( app.rb )
<h1>
<%= @restaurant.name %>
</h1>
<p><%= @restaurant.city %></p>
<a href="/">BACK</a>
class CreateRestaurants < ActiveRecord::Migration[5.1]
def change
create_table :restaurants do |t|
t.string :name
t.string :city
t.timestamps null: false
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment