Search code examples
ruby-on-railsrails-for-zombies

Rails for Zombies 1: Table names don't match access methods?


I've just moved onto the first Rails for zombie course which is about CRUD on a database.

What I don't understand and isn't explained is that there's a table called Zombies, but you access it using Zombie.find. Having just completed a course on standard Ruby, that to me looks like a Class and a method, but the Class isn't the same as the table name.

It was the same in the tutorial video - his table was called tweets, but he accessed it using Tweet.find. Shouldn't it be tweets.find?

Why don't the table names match the way you access those tables? How are you supposed to know which name to refer to the table as if it's not the same as the name of the table?


Solution

  • Rails automatically pluralizes your model name, which is Zombie, to use as the table name, zombies. The idea is that the model name represents one Zombie, while the table represents many Zombie's. When you're searching the table, it would make more sense to be able to use the name Zombies, but rails creates a class named Zombie for your model, and rather than create another class named Zombies, rails provides methods for your Zombie class, through inheritance, that allow you to search the table.

    At various points in your code, you will have to use the model name, Zombie, and at other points in your code, you will have to use the table name, zombies--experience and the docs and a close reading of your tutorial will alert you as to which to use.

    Note that rails will pluralize your model name Mouse--not to mouses--but to mice.

    Having just completed a course on standard Ruby, that to me looks like a Class

    Yes, Zombie is a class name. If you look in app/models/zombie.rb, you will see the class definition.

    And, if you look in db/migrate, you should see a file named 20130731063014_create_zombies.rb and inside that file will be a class named CreateZombies. rails uses classes all over the place.