Multiple Models and Relationships
Premium Content - Free Preview
Mr. Blackford, the store owner, has been happily storing products in the simple terminal application you set up. However, as he adds more products to the store, it becomes harder to browse through them to find a specific one. It would be great if there was a way to organize the products into categories.
Let's create a new model called Category and then figure out how to use it organize the products. For now Category will just have one custom column for its name, so let's generate it by entering the following command in the terminal:
rails generate model Category name:text
Note: if the Rails console is still running, exit it with Ctrl-C before entering the above command.
Then migrate it to setup the table:
== 20150324231527 CreateCategories: migrating ================================= -- create_table(:categories) -> 0.0012s == 20150324231527 CreateCategories: migrated (0.0013s) ========================
Databases are powerful because they let you connect different tables of data with each other. For example, we can easily classify products into categories.
Q: How can we classify the products into categories?
A: We need to identify each product with the category it belongs to. Let's add a new column
category_id to products to mark the category of each product.
Q: How can we get a list of all products in a specific category?
A: Simple. We just ask the computer to go through all the products and return the ones that belong to the category we want. For example, if we wanted the products in category 1, the computer would go through the database and return the products where the
category_id is 1.
Q: Will we need to write SQL to get this information?
A: No, Rails makes it easy for us. We just need to setup the columns and tell Rails about them.
Let's go ahead and add a new column to Products. Whenever we want to change a database in a Rails, we use a migration file. Earlier, we used a migration to create a new table for our model, but now we just need to add a new column. Enter the following code into your terminal:
rails generate migration AddCategoryIdToProducts category_id:integer
This will create a migration for adding a category_id column to products. Here's the general format for creating a migration to add
rails generate migration AddNameToTableName column_name:type
type specifies what data will be stored in the column, such as text or integer data. Once you've created the migration file, run
rake db:migrate to add the column to the database.