Skip to content

Instantly share code, notes, and snippets.

@kwaters12
Created March 6, 2014 17:44
Show Gist options
  • Save kwaters12/9395349 to your computer and use it in GitHub Desktop.
Save kwaters12/9395349 to your computer and use it in GitHub Desktop.
Active Record Notes
1. Retrieving Objects from the Database
Finder methods. All return an instance of ActiveRecord::Relation:
bind
create_with
eager_load
extending
from
group
having
includes
joins
limit
lock
none
offset
order
preload
readonly
references
reorder
reverse_order
select
distinct
uniq
where
1.1 Retrieving a Single Object
- using a primary Key - client = Client.find(10)
# finds a Client object with id: 10
- find_by - Client.find_by first_name: 'Lifo'
# Client with a first name of 'Lifo'
1.2 Retrieving Multiple Objects
- Using Multiple primary keys - Client.find([1,10])
# Finds Clients with ids 1 and 10
- take - Client.take(2) (first(2))
# Takes first 2 Client records
1.3 Retrieving Multiple Objects in Batches
# This is very inefficient when the users table has thousands of rows.
User.all.each do |user|
NewsLetter.weekly_deliver(user)
end
- Instructs Active Record to fetch the entire table in a single pass, build a model object
per row, then keep the entire array of model objects in memory.
User.find_each do |user|
NewsLetter.weekly_deliver(user)
end
- Retrieves a batch of records and then yields each record to the block individually as a model
- Change default amount of records using batch_size: User.find_each(batch_size: 5000)
# Give add_invoices an array of 1000 invoices at a time
Invoice.find_in_batches(include: :invoice_lines) do |invoices|
export.add_invoices(invoices)
end
- find_in_batches works like find_each, but returns the whole batch of records at a time,
instead of individually.
- :include allows you to name associations that should be loaded alongside the models.
2. Conditions
2.1 Pure String Conditions
- Client.where("orders_count = '2'") - find all clients where orders_count field's value is 2
2.2 Array Conditions
- Client.where("orders_count = ?", params[:orders]) - will go through the first element
in the conditions value and any additional elements
- Client.where("orders_count = ? AND locked = ?", params[:orders], false) - specify multiple conditions
This code is highly preferable:
Client.where("orders_count = ?", params[:orders])
to this code:
Client.where("orders_count = #{params[:orders]}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment