w3d4 Flashcards
What do ActiveRecord querying methods return?
An instance of ActiveRecord::Relation
When are Relation instances evaluated (i.e. a database query is fired)?
When they are directly accessed (i.e. via #each)
What happens to a Relation after a query is run?
After the query is run, the results are cached by Relation; they are stored for later re-use. Subsequent calls to each will not fire a query; they will instead use the prior result.
Say we want to re-fire a query after changing something in the db. What do we do?
Reload and ignore cached values by calling #query_method(true) on the instance in question.
What happens when we call ::where on a Relation?
A new Relation object is returned that reflects the query (note, however, that it is the existing relation that is queried, not the db. Furthermore, the already existing relation remains unchanged.)
What does #where_values do when called by a Relation?
It returns the results of the previous where query as a hash.
What happens when a method like #count is called on a Relation?
It forces the evaluation of a query, unlike most other query methods.
How can we force the evaluation of a query?
With #load.
How do we prefetch an association, and why bother?
By using
self.table_name.includes(:association_name)
This allows us the fire off the query based on the defined association, and avoids overhead by needing to run the query later.
What does prefetching association allow us to do?
Use iterative (N+1) methods on the prefetched data without the normal SQL query overhead.
For example, if we do the following:
comments = user.comments.includes(:post, :parent_comment)
Then all of the following will work without hitting the db:
comments[0].post
comments[0].parent_comment
comments.each do |comment|
How can we do a nested prefetch (for multi-level associations?)
posts = user.posts.includes(:comments => [:author, :parent_comment])
What does ::joins require?
An association given as a symbol argument.
What does ::joins return, and how is this different from what ::includes returns?
joins
does the opposite of includes
:
# includes
fetches the entries and the associated entries
both. User.joins(:comments)
returns no Comment
data, just
the User
columns. For this reason, joins
is used less
commonly than includes
.
What SQL operation does ::joins perform?
INNER JOIN
When should we use ::joins as opposed to ::includes?
When we want to do an aggregation (i.e. count), as opposed to a retrieval of all column values.