Unique but Same Validations

Kayla Budzeak
3 min readSep 3, 2021

This week I’ll be covering something that I encountered during one of my projects built while at Flatiron school; unique model validations.

I created an application to keep track of all of my World of Warcraft (WoW) characters. On WoW’s website, you can only view your characters by the server, but I wanted to see ALL of them all at once.

I was going through creating the seed data for my database with all of the Alliance and Horde races when something happened. I ran into the one race that was able to be linked to both factions; a user could choose instead of it being a set race. Say hello to the Pandaren race!

This was all fine and dandy until I started running my validations for the race model. I had set it up like so:

Can anyone see why my validations were failing? I sure couldn’t! So I let the Pandaren race fall by the wayside during project week, so that I could focus on other items. But I promised myself that I would come back to this after bootcamp and try to figure this darn thing out!

So after I graduated in February I came back to the project, with this issue glaring at me from the depths, and decided it was time to try and figure this out. I researched six ways to Sunday, and I finally saw what was happening. My validations, as I created them, were telling me that I could <i>only</i> have unique race names; there could be no duplicates. 🤦🏻‍♀️

Ok, so now how do I make it so that I still require unique race names, except for this one race?? Well, it turns out the answer is in the question. With an EXCLUSION validation tacked on.

Awesome! Now my validations pass! But wait a minute, I’ve been thrown another curveball. The validations pass, but when updating my seed data, I still only end up with one iteration of Pandaren: Horde. I’d already set up my seed data so that it wouldn’t just sit there and create duplicates every time I needed to update it by using Race.find_or_create_by(name: “”).

With Pandaren, it went through the data, found the Alliance iteration, then kept going and found the Horde one. Since the Horde one was the last one found and it had the name Pandaren, it overwrote the initial Alliance one, without creating its own. Challenge #2 accepted!

Turns out this one was also an “easy” fix. I needed to update my .find_or_create_by so that it looked for both name and faction.

Race.find_or_create_by(name: “Pandaren”, faction: “Alliance”).update_attributes(...)Race.find_or_create_by(name: “Pandaren”, faction: “Horde”).update_attributes(...)

Once I had created a record for both Alliance and Horde Pandaren with this fix, I was able to create, store and pass validations for an Alliance Pandaren and a Horde Pandaren.

--

--

Kayla Budzeak

I'm a Full-Stack Software Engineer, with a background in customer service, who recently graduated from Flatiron School. In my down time I love to bake & garden.