Object Relationships in Ruby explained by Relationships in Pokemons

Han Lee
Han Lee
Aug 5, 2016 · 2 min read

Recent Pokemon Go‘s huge success draws interests from many people. And, many people who grew up watching Pokemon shows are already familiar with Pokemon. So, Pokemon is a good example to explain Object Relationships in Ruby. The most famous pokemon is Pikachu, and its trainer is Ash. But, Pikachu is not the only pokemon Ash has. Ash has Bulbasaur, Charmander, and many others. To reflect that relationships in Ruby, Ash will be an instance of class Trainer, and Pikachu and other pokemons will be instances of class Pokemon. In terms of object relationships, a trainer has many pokemons and pokemons belong to a trainer.

Image for post
Image for post
Image for post
Image for post

If you have ever watched Pokemon, you must have seen Pikachu shooting electric thunderbolt attack. Each pokemon belongs to a type. For example, Pikachu is an electric type, which is why Pikachu can use thunderbolt attack.

Image for post
Image for post
From http://vsbattles.wikia.com/wiki/Pikachu

Other electric type pokemons include Electabuzz, Jolteon, and Pichu. If those relationships are applied to Ruby Object Relationships; a pokemon belongs to a type. A type has many pokemons. So, Pokemons belong to a trainer and belong to a type. A trainer has many pokemons and a type has many pokemons. A trainer has many types (pokemon types to be specific) through its pokemons and a type has many trainers through its pokemons. This is an example of a “has-many-through” relationship.

Image for post
Image for post

If you want to know what types of pokemons does Ash have, you can use; ash.pokemons.map{|pokemon| pokemon.type.name} to return them.

Image for post
Image for post
Image for post
Image for post

If you want to learn more about Object Relationships in Ruby, rubyonrails.org gives you excellent explanation of Object Relationships.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store