Managing Tables
So far we’ve been using migrations to manipulate the columns in existing tables. Now let’s look at creating and dropping tables:
| class CreateOrderHistories < ActiveRecord::Migration |
| def change |
| create_table :order_histories do |t| |
| t.integer :order_id, null: false |
| t.text :notes |
| |
| t.timestamps |
| end |
| end |
| end |
create_table takes the name of a table (remember, table names are plural) and a block. (It also takes some optional parameters that we’ll look at in a minute.) The block is passed a table definition object, which we use to define the columns in the table.
Generally the call to drop_table is not needed, as create_table is reversible. drop_table accepts a single parameter, which is the name ...
Get Agile Web Development with Rails 5, 1st Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.