Object Relationships in Ruby explained by Relationships in Pokemons

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.

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.

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.

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.

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