Skip to content

Instantly share code, notes, and snippets.

@leommoore
Created April 4, 2012 08:24
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 leommoore/2299680 to your computer and use it in GitHub Desktop.
Save leommoore/2299680 to your computer and use it in GitHub Desktop.
Rails Finders
#Primary key finder
Subject.find(2)
Returns an object or an error
#Dynamic Finders
Subject.find_by_id(2), Subject.find_by_name("First Subject")
Returns an object or nil
#Find all Method
Subject.all
Returns an array or objects
#First/last methods
Subject.first, Subject.last
Returns an object or nil
#New Methods
Subject.where(:visible => true)
Subject.where(:name => "First Subject")
Returns an ActiveRelation object
#Where Types
Subject.where("name = 'First Subject' AND visible = true) #String - Potential SQL Injection
Subject.where(["name = ? AND visible = true], "First Subject") #Array - Safe, flexible
Subject.where(:name => "First Subject", :visible => true) #Hashed - Safe, limited operators
#The methods can be chained. Execution is delayed until the data is needed
Subject.where(:visible => true).order("position ASC") #position is a field
Subject.where(:name => "First Subject").where(:visible => true)
Subject.scoped #This gives a blank ActiveRelation object to which you can add where clauses
subjects = Subjects.all
subjects.to_sql #Helps debugging to see what SQL was used
#Query Methods
Subject.order("position ASC").limit(20).offset(40)
Subject.order("subjects.visible DESC, subjects.name ASC")
#Named Scopes is a way to pre-define common queries for ease of use
class Subject < ActiveRecord::Base
scope :visible, where(:visible => true)
#scope with a variable
#Subject.search("Initial Subject")
scope :search, lamda {|query| where(["name LIKE ?", "%#{query}%"])}
end
#scope with multiple variables
#User.named("John", "Smith")
scope :named, lamda {|first,last| where(:first_name => first, :last_name => last)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment