2 title: Rails migrations
7 ### Automatically make migrations
9 $ rails generate migration RemovePartNumberFromProducts part_number:string
10 $ rails generate migration remove_part_number_from_products part_number # rails assumes string if not type given - and you can use snake_case
12 $ rails generate migration AddNameToWidgets name:string
13 $ rails g migration add_name_to_widgets name:string # you can use the short cut 'g' instead of generate - they both do the same thing
21 create_table :users do |t|
28 t.integer :games_count
31 t.decimal :price, :precision => 2, :scale => 10
32 t.datetime :expiration
47 add_column :users, :first_name, :string
48 remove_column :users, :first_name, :string
50 change_column :users, :first_name, :text
52 change_column_default :users, :admin, nil
53 change_column_null :users, :email, false # adds NOT NULL constraint
69 class AddFlagToProduct < ActiveRecord::Migration
70 class Product < ActiveRecord::Base
74 add_column :products, :flag, :boolean
75 Product.reset_column_information
77 dir.up { Product.update_all flag: false }
84 t.references :category # kinda same as t.integer :category_id
86 # Can have different types
87 t.references :category, polymorphic: true
89 ### Auto-Add/remove columns
91 $ rails generate migration RemovePartNumberFromProducts part_number:string
96 add_index :suppliers, :name
99 add_index :accounts, [:branch_id, :party_id], :unique => true
101 # Named (:name => ...)
102 add_index :accounts, [:branch_id, :party_id], :unique => true, :name => "by_branch_party"
105 add_index :accounts, :name, :name => ‘by_name’, :length => 10
106 add_index :accounts, [:name, :surname], :name => ‘by_name_surname’,
112 # Sort order (no MySQL support)
113 add_index :accounts, [:branch_id, :party_id, :surname],
114 :order => {:branch_id => :desc, :part_id => :asc}
117 Use `ActiveRecord::Migration`.
119 ActiveRecord::Migration.add_index :posts, :slug
123 * https://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index