Skip to content

Instantly share code, notes, and snippets.

@syamilmj
Forked from azinazadi/rails_cheatsheet.md
Created March 23, 2016 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syamilmj/c67341826c45a2244668 to your computer and use it in GitHub Desktop.
Save syamilmj/c67341826c45a2244668 to your computer and use it in GitHub Desktop.
Rails cheatsheet

An incomplete cheatsheet for rails 3. Things are added as they are required.

Active Record validations

# http://guides.rubyonrails.org/active_record_validations_callbacks.html

class SomeClass < ActiveRecord::Base

  # length
  validates :content, :length => {
    :minimum   => 300,
    :maximum   => 400,
    :tokenizer => lambda { |str| str.scan(/\w+/) },
    :too_short => "must have at least %{count} words",
    :too_long  => "must have at most %{count} words"
  }
  validates :name,
    :presence => true,
    :length => { :within => 1..255, :allow_blank => true }

  # format
  validates :legacy_code, :format => { :with => /\A[a-zA-Z]+\z/,
    :message => "Only letters allowed" }

  # in
  validates :size, :inclusion => { :in => %w(small medium large),
    :message => "%{value} is not a valid size" }

  # numericality
  validates :points, :numericality => true
  validates :games_played, :numericality => { :only_integer => true }    # Uses regex /\A[+-]?\d+\Z/

  # presence
  validates :order_id, :presence => true

  # uniqueness
  validates :email, :uniqueness => true
  validates :name, :uniqueness => { :scope => :year, :message => "should happen once per year" }
  validates :name, :uniqueness => { :case_sensitive => false }


  # allow_blank
  validates :title, :length => { :is => 5 }, :allow_blank => true

  # allow_nil
  validates :size, :inclusion => { :in => %w(small medium large),
    :message => "%{value} is not a valid size" }, :allow_nil => true

  # on
  validates :email, :uniqueness => true, :on => :create

  # conditionals
  validates :card_number, :presence => true, :if => :paid_with_card?

end

Caching

# http://railslab.newrelic.com/2009/02/19/episode-8-memcached
Rails.cache.read
Rails.cache.write
Rails.cache.fetch
Rails.cache.delete
Rails.cache.exist?
Rails.cache.increment
Rails.cache.decrement
Rails.cache.clear
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment