ActiveRecord::ConnectionAdapters::TableDefinition | column相关方法学习笔记

TableDefinition 的对象,就是我们在写 migrate 的时候使用的对象 t

如下

class SomeMigration < ActiveRecord::Migration
  def up
    create_table :foo do |t|
      puts t.class  # => "ActiveRecord::ConnectionAdapters::TableDefinition"
    end
  end

  def down
    ...
  end
end

column 方法语法是:
column (name, type, options = {})
type 可以是
:primary_key
:string
:text
:integer
:float
:decimal
:datetime
:timestamp
:time
:date
:binary
:boolean
你也可以不使用上面的类型,比如使用 MySQL 里的 polygon 类型,但是我们应该避免使用这些,这样我们的数据库模型才能兼容多种数据库.

可用的 options 是下面的这几种:
:limit 给定一个最大长度, 一般给 :string 和 :text 指定, 或者是指定给 :binary 表示二进制数据的字节数, 而给定 :integer 则表示允许的位数。

:default 指定字段的默认值,使用nil 来表示NULL
:null 是否允许字段为NULL ,也可以用 :null_allowed 来指定这一项。
:precision 为 :decimal 字段指定有效位的数量( 不包含小数点等)
:scale 为 :decimal 指定允许小数点后面有几位.

我们假定 t 为 TableDefinition 的实例。

t.column(:granted, :boolean)
# granted BOOLEAN

t.column(:picture, :binary, limit: 2.megabytes)
# => picture BLOB(2097152)

t.column(:sales_stage, :string, limit: 20, default: 'new' , null: false)
# => sales_stage VARCHAR(20) DEFAULT 'new' NOT NULL

t.column(:bill_gates_money, :decimal, precision: 15, scale: 2)
# => bill_gates_money DECIMAL(15,2)

t.column(:sensor_reading, :decimal, precision: 30, scale: 20)
# => sensor_reading DECIMAL(30,20)

# 在大多数数据库中,:scale 一般为 0 ,我们可以不指定它
t.column(:huge_integer, :decimal, precision: 30)
# => huge_integer DECIMAL(30)

# 指定某种数据库特有的类型
t.column(:foo, 'polygon')
# => foo polygon

一般地,像下面这种定义,我们可以使用类型方法简化它

create_table :products do |t|
  t.column :shop_id,    :integer
  t.column :creator_id, :integer
  t.column :name,       :string, default: "Untitled"
  t.column :value,      :string, default: "Untitled"
  t.column :created_at, :datetime
  t.column :updated_at, :datetime
end

我们可以使用更简便的方式来完成上面代码的工作:

create_table :products do |t|
  t.integer :shop_id, :creator_id
  t.string :name, :value, default: "Untitled"
  t.timestamps
end

references方法 将添加字段并用后缀命名为 xxx_id , 如果指定了 :polymorphic 项, 会增加一个 xxx_type 字段。如果:polymorphic 的值为 hash 类型,当你想创建 xxx_type 字段是,就会很有用。 也可以指定 :index 来添加索引, 就象使用 add_index 方法一样。具体如下:

create_table :taggings do |t|
  t.integer :tag_id, :tagger_id, :taggable_id
  t.string :tagger_type
  t.string :taggable_type, default: 'Photo'
end
add_index :taggings, :tag_id, name: 'index_taggings_on_tag_id'
add_index :taggings, [:tagging_id, :tagger_type]

使用下面代码也能完成上面的操作

create_table :taggings do |t|
  t.references :tag, index: {name: 'index_taggings_on_tag_id'}
  t.references :tagger, polymorphic: true, index: true
  t.references :taggable, polymorphic: {default: 'Photo' }
end
原文地址:https://www.cnblogs.com/laoquans/p/3984811.html