In Rails 4, different from 3, when calling the method all
Active Record does not return a Array
, but an object child of ActiveRecord::Relation
. Once the darlings return this Relation
, now we can chain our queries so that they produce only one sql:
Client.all.where("name = ?", "Juliano")
=> Client Load (0.7ms) SELECT "clients".* FROM "clients" WHERE (name = 'Juliano')
However, doing as you asked, Activerecord will generate two queries, since they are not chained. The valuations object is a Relation, so it will rather make a call to the database.
For it to be single access in the bank, you must chain the two calls. If not possible, you can handle the result already in memory with the method select
:
avaliacaoes = Avaliacao.all
avaliacoes.select {|a| a.score == 3}
Errata
As pointed out by @Guigs, part of my reply should be corrected. When you use Relation more than once in the same method, it will only be evaluated at the end, so your code will only do one search in the database, although the calls are not visibly linked (obj.metodo1.metodo2) they will be evaluated only when data is required.
It is only important to note that if you have several conditions, some may be ignored.
avaliacaoes = Avaliacao.all
avaliacoes.where("score = ?", 3)
avaliacoes.where("score = ?", 2)
Will generate
=> Avaliacao Load (0.7ms) SELECT "avaliacoes".* FROM "avaliacoes" WHERE (score = 2)
Sorry for the mistake, I fell for this because I tested my answer directly on the console, then each evaluation was done immediately. My bad! ;)
In Rails 4 o
where
method accepts a hash:Avaliacao.where(score: 1)
- you don’t needall
.– Mohamad