agaskar.com

Feb 20 2010

Active Record DB Types: A Reference

Native types:

add_column :native_type, :name, :options
:primary_key 
:string 
:text
:integer 
:float
:decimal
:datetime
:timestamp 
:time 
:date 
:binary 
:boolean

Native Type Options:

:limit - Requests a maximum column length. This is number of characters for :string and :text columns and number of bytes for :binary and :integer columns.
:default - The columnā€˜s default value. Use nil for NULL.
:null - Allows or disallows NULL values in the column. This option could have been named :null_allowed.
:precision - Specifies the precision for a :decimal column.
:scale - Specifies the scale for a :decimal column.

Table definitions:

  create_table :products do |t|
    t.integer :shop_id, :creator_id
    t.string  :name, :value, :default =%gt; "Untitled"
    t.timestamps
  end
You can use any native type, or the following helpers.

timestamps

adds created_at and updated_at timestamp columns to your table.
...
t.timestamps
...

references

Adds the integer field “#{name}_id”. Also adds the string field “#{name}_type” if polymorphic is true. You can pass a hash to polymorphic and specify a default if desired.
create_table :taggings do |t|
    t.references :tag
    t.references :tagger, :polymorphic => true
    t.references :taggable, :polymorphic => { :default => 'Photo' }
  end

Auto-generate an add_column migration

There is a special syntactic shortcut to generate migrations that add fields to a table.
 script/generate migration add_fieldname_to_tablename fieldname:string

Comments (View)
Page 1 of 1
blog comments powered by Disqus