rails migration add column code example

Example 1: how to add column to table rails

rails g migration add_description_to_users description:string
#'g' means generate, the 'add' in 'add_description_to_users' tells
#Rails you want to add a column, the 'description' is the new column name,
#and the 'users' is the table you want to add it to, must be plural. 
#After you've checked your migration to make sure its what you want...
rails db:migrate

Example 2: how create migration rails

rails g migration AddPartNumberToProducts

Example 3: rails g migration add columns

$ rails generate migration AddDetailsToProducts part_number:string price:decimal

Example 4: activerecord add column

class AddPartNumberToProducts < ActiveRecord::Migration[6.0]
  def change
    add_column :products, :part_number, :string
  end
end

Example 5: how to create an SQL table in ruby

def self.create_table
    sql = <<-SQL
      CREATE TABLE IF NOT EXISTS students (
        name TEXT,
        grade TEXT
      )
    SQL
    DB[:conn].execute(sql)
  end

Example 6: rails model column

class AddColumnTitles < ActiveRecord::Migration
  def up
    add_column :titles, :place, :string
  end

  def down
    remove_column :titles, :place, :string
  end
end

Tags:

Sql Example