Skip to content

Instantly share code, notes, and snippets.

@wojtha
Forked from taktran/rails_cheatsheet.md
Created October 6, 2016 16:02
Show Gist options
  • Save wojtha/f36d60d9377393e2977730ece27acf30 to your computer and use it in GitHub Desktop.
Save wojtha/f36d60d9377393e2977730ece27acf30 to your computer and use it in GitHub Desktop.
Rails cheatsheet

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

## Debugging

Check errors

@user = User.new(:email => email)
puts @user.valid?
@user.errors.each { |e| puts "#{e}: #{@user.errors[e]}" }

Logging

log = Logger.new("log/debug.log")
log.debug("Hello debug")

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