DEV Community

anette87
anette87

Posted on

Sinatra, Active Record and Associations.

As a Software Engineering student, the idea of creating your first “real” web application is like a dream come true. I couldn’t be more excited about learning how to use Sinatra and I couldn’t wait for project week.

What is Sinatra? Sinatra is an open-source software web application library and DSL (domain-specific language) written in our old and good friend Ruby. Sinatra focuses on creating web-applications quickly and in some level “easy”. I said on some level because yes, technically building the app structure with Sinatra is easy, but if you don’t know how to work with your MCV (models, controllers and views) it’s pretty much impossible to build a functional app.

Something that has been a challenge for me since we started learning about it is Associations. I understand the idea and make total sense, but for some reason was (and sometimes is) difficult to understand how to connect all the pieces. Thanks to Active Record now everything is way more clear and easy.

One good example of this is my Sinatra Project. My app is about creating a list of your favorites Disneyland rides and having the option to add reviews to all the rides. At some point in the project, I had to create a list of all the rides by location. I thought the easiest way to do it was thru my Ride model using the location attribute to call the location and from there list the rides with the same location. To do this I created a self.location and self.by_land method and after that a Helper method to be able to use self.by_land inside my views (sounds like a lot of work right? IT WAS).

Alt Text

Everything work and I was proud of my amazing methods but after having my 1:1 meeting with my coach she made me realize that yes, everything work just fine but the right way to do that was creating a location object and just use associations to create my list. After our call, I started working with that and I was just impressed with how easy it was to create my list just by using the associations and everything took me around 15 minutes. My ride belongs_to a location and my location has_many rides. Just as simple as that. I don’t need to build any other method because Active Record took care of that when I create my associations.

Alt Text
Alt Text
Alt Text

Pretty amazing right?

Active Record associations are a great tool and are here to make our lives easier. My new goal as a programmer is to identify when (while I’m building my applications) makes more sense to create an object and build associations between two Active Record models instead of just using attributes that at the end can probably get the job done but it would take way more time than necessary and as you know we, programmers, are lazy (but in a good way).

Thank you for reading!

Discussion (0)