I want to build a very simple sinatra app, but I also want it to connect to the database. Here is the walk through for how to have a very base install, which includes migrations.
The final code is available at wschenk/sinatra-ar-template.
Setup the base
Add up your Gemfile:
| |
Simple config.ru
| |
Dockerize
A pretty standard Dockerfile:
| |
Rake tasks
And now a Rakefile, where we add runner tasks, docker tasks, as well
as the activerecord migration tasks.
| |
Setup the app
Now an app.rb
| |
Database Config
First create a directory for the database.yml file:
| |
Then setup sqlite3:
| |
| |
| |
Create a model
We'll begin by creating 2 directories, one that stores the model logic and the other which defines the routes
| |
Database
Let's add a model, for example post
| |
db/migrate/20230930213922_post.rb
Then we can add our fields to it to it
| |
Then create the table
| |
| |
And we can verify that it's there
| |
| |
Code
First the model, where we tell it we need to have some required fields
| |
Then the routes itself, where we either return a list of all the posts or we create a post and return it.
| |
Testing it out
Start the server
| |
Then we can test this out:
| |
| |
Add a post
| |
| |
Then we can see the results:
| |
| |
We can also try to add a post that's missing a required field:
| |
| |
Adding a password
Lets see how to add authentication.
| |
Create the migration and run it:
| |
db/migrate/20230930221648_account.rb
| |
| |
| |
Add the model and the route
| |
Then lets add some routes for it:
| |
Test account creation
Empty password confirmation
| |
| |
Not matched password confirmation
| |
| |
Happy path
| |
| |
Trying a double signup
| |
| |
Testing login
Unauthenticated access
| |
| |
Login and store the cookie in the jar!
| |
| |
Pass in the session cookie
| |
| |
Create a model
Add a migration, for a table called for example poi
rake db:create_migration poiHere is an example migration
| |
Then we can run it:
| |
| |
Check out the table
| |
| |