Created
April 4, 2012 08:24
-
-
Save leommoore/2299680 to your computer and use it in GitHub Desktop.
Rails Finders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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