Skip to content

Instantly share code, notes, and snippets.

@mikesjewett
Created December 10, 2012 16:11
Show Gist options
  • Save mikesjewett/4251548 to your computer and use it in GitHub Desktop.
Save mikesjewett/4251548 to your computer and use it in GitHub Desktop.
Bloc Rails Cheatsheet

Common validation helper methods (called in model)

Presence: ensures that a field is present upon submission

validates :name, :email, presence: true

Acceptance: ensures that a checkbox has been checked

validates :terms_of_service, acceptance: true

Format: validates against regexp and returns message if it doesn't pass

validates :email, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i, message: "Valid email required" }

Length: validates length with an optional hash for maximum

validates :tweet, length: { maximum: 140 }

Numericality: validates numericality with an optional hash for integer

validates :age, numericality: { only_integer: true }

Uniqueness: uniqueness should always be ensured at the database level as well

validates :email, uniqueness: true

Data definition methods

create_table
change_table
drop_table
add_column
change_column
rename_column
remove_column
add_index
remove_index

# Usage example
def self.up 
  create_table :users do |t|
    t.string :email, null: false
    t.datetime :dob
    t.timestamps
  end
  add_index :users, :email, unique: true
end

def self.down
  drop_table :users
end

rake db:migrate # run up methods
rake db:rollback # run down method
rake db:rollback STEP=3 #run last 3 down methods

Data Types for Table object

primary_key
string
text
integer
float
decimal
datetime
timestamp
time
date
binary
boolean

Rake Tasks

rails g migration <name>
rake db:migrate
rake db:rollback

# Example usage for migration
rails g migration add_email_to_users email:string
# automatically creates:
def change
  add_column :users, :email, :string
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment