Rails automatically caches the result of database calls. From the Rails Guides:
Query caching is a Rails feature that caches the result set returned by each query. If Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.
For example:
class ProductsController < ApplicationController
def index
# Run a find query
@products = Product.all
...
# Run the same query again
@products = Product.all
end
end
The second time the same query is run against the database, it's not actually going to hit the database. The first time the result is returned from the query it is stored in the query cache (in memory) and the second time it's pulled from memory.
However, it's important to note that query caches are created at the start of an action and destroyed at the end of that action and thus persist only for the duration of the action. If you'd like to store query results in a more persistent fashion, you can with low level caching.
My recommendation is not to assign it to a variable because it does nothing to improve the readability of the code and the performance difference is negligible. It could introduce confusion; if I were reading the code and saw someone replaced all calls to documents
with docs
I would wonder why and would have to take time to understand why.
Ultimately, setting docs = self.documents
just tells Ruby "docs
should point at the same memory location as self.documents
", and regardless of which one you call Ruby will return the same data from the same memory location. There is a performance difference between calling a method and calling a variable, but that performance difference is so minor in comparison to something like the speed of a database call that it can be ignored; there are much better ways to improve the performance of an app than switching method calls to variable calls.
If your concern is that you don't want to type out documents
over and over again when you could just type docs
, then use alias_method
:
class User < ApplicationRecord
has_many :documents
alias_method :docs, :documents
end
Then there is no difference between calling user.documents
and user.docs
-- they call the same method. But again, does it do anything to improve readability of the code? In my opinion, no.
Stick with calling documents
.