Skip to content

Instantly share code, notes, and snippets.

@Atlas7
Last active January 22, 2016 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Atlas7/eb4a28106079182213f2 to your computer and use it in GitHub Desktop.
Save Atlas7/eb4a28106079182213f2 to your computer and use it in GitHub Desktop.
CodeSchool - Ruby-on-Rails - Find all weapons that belong to a zombie "Ashley"

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:

zombie_weapons_model.png

And the equivalent database that looks like this:

zombie_weapons_database.png

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:

Rails Guide - Active Record Querying

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment