I am relatively new to Ruby on Rails and am going through some tutorials to understand the stuff which is generated via the rails g
command. In this case, generating a customer model with a username and email string produces the following migration file:
class CreateCustomers < ActiveRecord::Migration[6.1]
def change
create_table :customers do |t|
t.string :username
t.string :email
t.timestamps
end
end
end
I understand that create_table
is a method which has the symbol of :customer
passed in as a param. I also understand that there is a block being passed into said method. However, what I do not understand is what the t
inside the block exactly represents. Any help in helping me understand this would be very much appreciated.
The migration file is a set instruction to your database to create a new table named 'customers' with two string fields, username and email. 't' just represents this table. Even though it only iterates over it once, it is following the general form of:
@items.each do |item|
If you are using a SQL database, when you run rails db:migrate
these instructions will be turned into SQL and executed in the database. The SQL will be something like:
CREATE TABLE customers(
id BIG_INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(256),
email VARCHAR(256)
);