Picture of Michael Lee
:wave: Hey hey, I'm Michael Lee and this is my site about being a developer, being a dad and making side projects.
Sponsorship

Frustration with defining relationships

Written on September 15, 2018

The past few days have been pretty frustrating with ConfsList. Mainly because I wasn’t making any real progress. I had been stuck on defining relationships these past few days until yesterday.

In ConfsList, I’ve got a model for events and with each event, there is a location that goes with it. In ConfsList, location is also another model. For the past three days, I had been defining the relationship so that each event has a location.

Initially I tried having the event model to have a single location using Rails’ has_one and on the location side saying that each location belongs_to an event.

On the view, I wanted for the user to assign a location to the event when it was being created. This would be done by passing a location_id to the event model. But for some reason this didn’t work for me.

So upon looking over the ActiveRecord docs again, I tried redefining the relationship as a has_many on both sides through a join table. Setting this up wasn’t too bad, but again when trying to pass the location_id with the new event form, Rails would complain about the parameter not being allowed.

I had fixated on trying to get the application to work with this relationship by trying to tweak the parameters and the models. But to no end, I couldn’t figure it out. During this time I got frustrated and was super tempted to switch back to Node. Since I wouldn’t have to work about using ActiveRecord and just define the model and relationships by hand.

But I was determined to make it work. It wasn’t until I started to think about how I would solve it in Node. That I would assign a column on the event model with location_id and have the event reference location objects. It was then it clicked to me that I might have the relationship defined incorrectly.

Upon reading about ActiveRecord relationships, I realized that in order to get the event model to have a column of location_id in its table. I had to have the event belong_to and the location has_many defined in the model. Once I had switched this and created a migration for my database, it worked the way I had expected it.

Where there would be a limited set of locations, but each location could potentially have multiple events. It’s instances like this where relational databases confuse me. But I do feel like I have a better understanding of ActiveRecord because I had been struggling with it for 3 full days.

Thanks for taking the time to read this article. I'd love to stay in touch and share more tips on programming and design and side projects. Sign up and I'll send you my articles straight to your email.