What I Learned From My First Sinatra Project

Parham Javadi
2 min readMar 25, 2021

--

Writing Code in HTML

I created my first web application using Ruby Sinatra and HTML. Although I had prior experience with HTML and CSS, I never actually wrote code in my HTML, so this was the first time I learned to implement some code in my HTML files. At first, I did not get the difference between <% and <%= , and my code was not working due to using the wrong syntax until I realized that <% is just for us developers to use logic such as iterating through an array, and <%= is what the user sees. Below is a snippet of my code.

<% current_user.hospitals.each_with_index do |hospital, i| %><%= i + 1 %>.  Hospital Name: <%= hospital.hospital_name %> | Hospital Country: <%= hospital.hospital_country %><% end %>

Since we are iterating to get a list of all the hospitals, we need to use <% and if we want to display something to the user (hospital.hospital_name ), we would use <%= .

Another important thing I learned is when we are creating a form in HTML, we need to pay attention to action= and method= attributes. The link we add to the action attribute needs to match the link we added in our controller file under get and/or post . Now, it matters when we use method=get or method=post; this link will point out some of key differences between the two.

The Power of Active Records

After I learned about Active Records, I must say that it makes everything a lot simpler and saves time. The CRUD (Create, Read, Update, Delete) is what makes tasks easier to achieve. Also, Instead of using SELECT * FROM hospitals and pushing all the data into an array, I can simply do Hospitals.all to get all the hospitals.

Basic Associations

Another great feature of Active Records are the basic associations such as has_many and belongs_to relationships. My Model has a class of User and Hospital . A User has_many :hospitals , and a Hospital belongs_to :user . I had the assumption that as long as we state that a hospital belongs to user, the User will know that it has many hospitals, but after getting a lot of syntax errors, I learned that Rails will not know about this relationship unless we assign the user_id column to Hospital . By doing so, we are telling Ruby which user actually owns the hospital because each user needs to have its own hospital, and a user should always modify its own hospital, not hospitals created by other users.

--

--