Migration
正常方式生成model和migration
rails g model Product name:string description:text
上面的命令会创建下面的migration
class CreateProducts < ActiveRecord::Migration[5.0]
def change
create_table :products do |t|
t.string :name
t.text :description
t.timestamps
end
end
end
创建数据表CreateXxx
rails g migration CreateProducts name:string part_number:string
上面命令生成
class CreateProducts < ActiveRecord::Migration[5.0]
def change
create_table :products do |t|
t.string :name
t.string :part_number
end
end
end
创建新migration来添加字段AddXxxToYyy
rails g migration AddPartNumberToProducts
上面命令生成
class AddPartNumberToProducts < ActiveRecord::Migration[5.0]
def change
end
end
AddXxxToYyy + column:xxx
rails g migration AddPartNumberToProducts part_number:string
上面代码会生成
class AddPartNumberToProducts < ActiveRecord::Migration[5.0]
def change
add_column :products, :part_number, :string
end
end
还可以添加索引
rails gmigration AddPartNumberToProducts part_number:string:index
上面代码生成
class AddPartNumberToProducts < ActiveRecord::Migration[5.0]
def change
add_column :products, :part_number, :string
add_index :products, :part_number
end
end
新建migration用于删除字段RemoveXxxFromYyy
rails g migration RemovePartNumberFromProducts part_number:string
上面命令会生成
class RemovePartNumberFromProducts < ActiveRecord::Migration[5.0]
def change
remove_column :products, :part_number, :string
end
end
还可以用于删除多个字段
rails g migration AddDetailsToProducts part_number:string price:decimal
上面代码生成在这里插入代码片
class AddDetailsToProducts < ActiveRecord::Migration[5.0]
def change
add_column :products, :part_number, :string
add_column :products, :price, :decimal
end
end
创建数据表create_table
create_table :products do |t|
t.string :name
end
修改数据表change_table
change_table :products do |t|
t.remove :description, :name
t.string :part_number
t.index :part_number
t.rename :upccode, :upc_code
end
创建联结数据表create_join_table
create_join_table :products, :categories
可以通过:table_name来定义联结数据表的名称
create_join_table :products, :categories, table_name: :categorization
create_join_table也接收块,用于添加索引
create_join_table :products, :categories do |t|
t.index :product_id
t.index :category_id
end