Writing a web application using Sinatra and Databases

Stephen Dawes
canitbedone
Published in
2 min readJun 14, 2016

So this week our challenge has been to write a basic web application, using Ruby, Sinatra, RSpec, Capybara, SQL, PostgreSQL and DataMapper. Last week was difficult enough, jut writing a basic web app using Ruby and Sinatra, but adding in the complexity of databases has made it a real challenge.

I won’t go through every step and every detail of what we have and will be covering over the next week — but touch on a few interesting challenges I have faced over the last couple of days. Simply put, our challenge is to create a bookmark manager, akin to pineapple.io, to create and view links, assign tags to them and filter by tags.

The first issue I faced was with regards to tables and in particular, Object Relational Mapping and the notion of many to many relationships with tables. This has been something of a mind meddle.

Getting to grips with setting up a ‘data_mapper_setup.rb’ file and creating tables automatically through ruby code, linking them through class initialization in the main controller, managing them in the model files and outputting results in the view files, has been somewhat ‘difficult’.

Confounding this has been attempting to understand the detail in how to relate the different tables and create a ‘many to many’ relationship, in order to assign and then filter by tags.

Some example code to demonstrate these issues is as follows:

  post links in the controller file   post '/links' do
link = Link.create(title: params[:title], url: params[:url])

params[:tags].split.each do |tag|
link.tags << Tag.first_or_create(name: tag)
end

link.save
redirect to '/links'
end
Link class to create table 'links' class Link
include DataMapper::Resource
has n, :tags, through: Resource property :id, Serial
property :title, String
property :url, String
end
Obtaining information to create the tables and relationships, from a form in an erb file<h1>Links</h1>
<ul id=”links”>
<% @links.each do |link| %>
<li>
Title: <%= link.title %>
URL: <%= link.url %>
</li>
<% end %>
</ul>

I will continue to update this post as the rest of the week progresses!

--

--

Stephen Dawes
canitbedone

16 years working in aviation. Leaving to change direction. In my late 30s with no previous knowledge of programming or web development. Can this really be done?