Skip to content

Instantly share code, notes, and snippets.

@thomasmarren
Last active October 18, 2016 12:32
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 thomasmarren/400a26f9e1f61217563ab2e9b048ccf6 to your computer and use it in GitHub Desktop.
Save thomasmarren/400a26f9e1f61217563ab2e9b048ccf6 to your computer and use it in GitHub Desktop.
User.find(10)
=> #<User id: 10, name: => "Tom">
User.find(1, 10) #or ([1, 10])
=> #[<User id: 1, name: => "Lifo">, #<User id: 10, name: => "Ryan">]
User.first
User.last
User.all
#User.all makes Active Record fetch the entire table, build a model object per row,
#and keep the entire array in the memory. find_each can iterate over data in a
#table in batches which is useful with tables of thousands of rows
User.find_each(:batch_size => 5000) do |user|
NewsLetter.weekly_deliver(user)
end
#Checks if User with an id exists
User.exists?(1,2,3)
#All SQL calculations can be used with Active Record methods
User.count
User.average("age")
User.minimum("age")
User.maximum("age")
User.sum("age")
# .where finds based on a condition
User.where("age = 20")
#Group by a specific characteristic
User.group(:name)
#Order by a characteristic
User.order(:name)
#Run pure SQL using Active Record
User.find_by_sql("SELECT * FROM users WHERE age > 20")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment