Rails - Migrationcheatsheet
贡献者:BAI
Rails - Migration
自动创建迁移
SHELLrails generate migration RemovePartNumberFromProducts part_number:stringrails generate migration remove_part_number_from_products part_numberrails generate migration AddNameToWidgets name:stringrails g migration add_name_to_widgets name:string
执行迁移
SHELLrake db:migrate
创建表
RUBYcreate_table :users do |t| t.string :name t.text :description t.primary_key :id t.string :title t.text :description t.integer :games_count t.float :lol t.decimal :price t.decimal :price, :precision => 2, :scale => 10 t.datetime :expiration t.timestamp :time_in t.time :time_in t.date :expiry t.binary :image_data t.boolean :is_adminend# Options: :null (boolean) :limit (integer) :default
具体操作
RUBYadd_column :users, :first_name, :stringremove_column :users, :first_name, :stringchange_column :users, :first_name, :textchange_column_default :users, :admin, nilchange_column_null :users, :email, false # 添加不允许为空的约束create_tablechange_tabledrop_tableadd_columnchange_columnrename_columnremove_columnadd_indexremove_index
模型用法
RUBYclass AddFlagToProduct < ActiveRecord::Migration class Product < ActiveRecord::Base end def change add_column :products, :flag, :boolean Product.reset_column_information reversible do |dir| dir.up { Product.update_all flag: false } end endend
关联(Association)
RUBYt.references :category # 与 t.integer :category_id 等效 t.references :category, polymorphic: true
自动增、减列
RUBYrails generate migration RemovePartNumberFromProducts part_number:string
索引
RUBYadd_index :suppliers, :nameadd_index :accounts, [:branch_id, :party_id], :unique => trueadd_index :accounts, [:branch_id, :party_id], :unique => true, :name => "by_branch_party"add_index :accounts, :name, :name => ‘by_name’, :length => 10add_index :accounts, [:name, :surname], :name => ‘by_name_surname’, :length => { :name => 10, :surname => 15 }add_index :accounts, [:branch_id, :party_id, :surname], :order =>
在 Console 中
Use ActiveRecord::Migration
.
RUBYActiveRecord::Migration.add_index :posts, :slug