Migrations Flashcards
How to create a simple migration?
rails g migration sample
How to generate a migration with a table creation?
# create and table name are keywords there rails g migration create_table_name
creates
def change
create_table :table_names do |t|
end
end
How to generate a migration to create table with a column field?
rails g migration create_table_names name:string
creates
def change create_table :table_names do |t| t.string :name end end
How to generate a migration to remove a column?
# you need to use Remove and From rails g migration RemoveColumnFromTableName sample
creates
def change
remove_column :table_names, :sample, :string
end
How to generate a new column with an index?
rails g migration AddSampleToTableName sample:string:index
How do rails know which migration should be run or not?
Rails create a row with a timestamp in schema_migrations table after each running migration.
How to run and rollback migration?
rails db:migrate
rails db:rollback
How to use up/down inside migrations?
# up runs on db:migrate # down runs on db:rollback
How to create a table inside a migration?
create_table :hello
How to create a table with a field?
create_table :hello_world do |t|
t.column :sample, :string
end
How to create a table with a field?
create_table :hello_world do |t|
t.column :sample, :string
end
What are the differences between :decimal and :float?
:decimal - Stored with specified precision. Use for math that requires accuracy.
:float - Floating-point decimal number with fixed precision depending on platform. Do not use for math that requires accuracy due to rounding errors.
How to create a table with a field and index?
create_table :hello_world do |t|
t.column :sample, :string
t.index :sample
end
How to add belongs_to association on migration?
# references create_table :hello_world do |t| t.references :dog end # belongs_to create_table :hello_world do |t| t.belongs_to :dog end # add column with index create_table :hello_world do |t| t.column :dog_id, :integer t.index :dog_id end
How to add belongs_to association on migration? ( 3 ways)
# add column with index create_table :hello_world do |t| t.column :dog_id, :integer t.index :dog_id end # references create_table :hello_world do |t| t.references :dog end # belongs_to create_table :hello_world do |t| t.belongs_to :dog end