Thursday, August 25, 2016

git add with sophictication

I found this git command that I have been looking for forever.
I used to use it then I forgot it and have been googling for it ever since/.

The perfect pairing to git add -p, drum roll please...

git add . -N && git add -p
  • The -N flag means is short for --intent-to-add 
  • git add . -N will stage an empty file representing your newly added file.
    When git add --patch is called 
  • Git will do the normal patch procedure over your newly created file's changes.
  • If no changes are patched in,
    the empty file will not be included in your commit.

Always be sure to check your status!

Sunday, August 14, 2016

Rails Cheat Sheet: Create Models, Tables and Migrations

Create a new table in Rails

rails g model Supplier name:string
rails g model Product name:string:index sku:string{10}:uniq count:integer description:text supplier:references popularity:float 'price:decimal{10,2}' available:boolean availableSince:datetime image:binary
Resulting migrations:
class CreateSuppliers < ActiveRecord::Migration
  def change
    create_table :suppliers do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name
      t.string :sku, limit: 10
      t.integer :count
      t.text :description
      t.references :supplier, index: true, foreign_key: true
      t.float :popularity
      t.decimal :price, precision: 10, scale: 2
      t.boolean :available
      t.datetime :availableSince
      t.binary :image

      t.timestamps null: false
    end
    add_index :products, :name
    add_index :products, :sku, unique: true
  end
end

Rails migration to add a column

rails g migration AddKeywordsSizeToProduct keywords:string size:string
Resulting migration:
class AddKeywordsSizeToProduct < ActiveRecord::Migration
  def change
    add_column :products, :keywords, :string
    add_column :products, :size, :string
  end
end

Rails migration to remove a column

rails g migration RemoveKeywordsFromProduct keywords
Resulting migration:
class RemoveKeywordsFromProduct < ActiveRecord::Migration
  def change
    remove_column :products, :keywords, :string
  end
end

Rails migration to rename a column

rails g migration RenameProductPopularityToRanking
You need to add the rename_column command manually to the resulting migration:
class RenameProductPopularityToRanking < ActiveRecord::Migration
  def change
    rename_column :products, :popularity, :ranking
  end
end

Rails migration to change a column type

rails g migration ChangeProductPopularity
You need to add the change_column command manually to the resulting migration:
class ChangeProductPopularity < ActiveRecord::Migration
  def change
      change_column :products, :ranking, :decimal, precision: 10, scale: 2
  end
end

Running migrations

rake db:migrate
In production:
rake db:migrate RAILS_ENV="production"