Columns store data in a database table. Different types hold different kinds of information.
0
0
Column types and attributes in Ruby on Rails
Introduction
When creating a new database table to store user information.
When adding a new feature that needs to save dates or numbers.
When defining what kind of data each column should hold to keep data organized.
When setting rules like making sure a column cannot be empty.
When optimizing storage by choosing the right data type for each column.
Syntax
Ruby on Rails
create_table :table_name do |t| t.column_type :column_name, options end
Replace column_type with the type like string, integer, or boolean.
Options can include null: false to require a value or default: value to set a starting value.
Examples
This creates a text column for short strings.
Ruby on Rails
t.string :name
# Stores text data like names or titlesThis column must have a number and starts with 0 if no value is given.
Ruby on Rails
t.integer :age, null: false, default: 0 # Stores whole numbers, cannot be empty, starts at 0
Good for flags like if a user is active or not.
Ruby on Rails
t.boolean :active, default: true
# Stores true or false values, defaults to trueUsed to track when something was created or updated.
Ruby on Rails
t.datetime :created_at
# Stores date and time informationSample Program
This migration creates a users table with columns for username, age, admin status, and join date. It also adds timestamps for created_at and updated_at automatically.
Ruby on Rails
class CreateUsers < ActiveRecord::Migration[7.0] def change create_table :users do |t| t.string :username, null: false t.integer :age, default: 18 t.boolean :admin, default: false t.datetime :joined_at t.timestamps end end end
OutputSuccess
Important Notes
Always pick the smallest column type that fits your data to save space.
Use null: false to make sure important data is always there.
Default values help avoid errors when no data is given.
Summary
Columns define what kind of data a table holds.
Choose types like string, integer, boolean, or datetime based on your data.
Use attributes like null and default to control data rules.