This post is inspired by this Code School Rails Tutorial.
Notes:
- Model name is also singular, begin with a capital letter.
- if a model is used as a method, that model name becomes all lower case. Singular / Plural depends on the model.
Say we have a Model that looks like this:
And the equivalent database that looks like this:
Quesiton:
Find all weapons that belong to the zombie called "Ashley".
Answer:
This is my one-liner Rails query:
Zombie.where(name: 'Ashley').take.weapons
Output:
<ActiveRecord::Associations::CollectionProxy [#<Weapon id: 1, name: "Hammer", strength: 1, zombie_id: 1>]>
Further Readings: