Filtering on activerecord relation without additional sql query?
20,734
The ActiveRecord:Relation
only queries the db when its elements are accessed. So the sequence you have will not call the db at all unless you write something like u.first
or tens.first
.
It is a bit different in Rails console as each statement results are printed to console so it executes the query each time. You can skip the printing by appending ; 1
after each statement.
That aside, if you still want to filter the results with first query:
u = User.where(name: "bob", age: [10, 20]) # no query at this point
u.class # ActiveRecord::Relation
u.first # query to db
u.class # Array
tens = u.select{|x| x.age == 10} # no query to db
Author by
Derek
Updated on October 24, 2020Comments
-
Derek over 3 years
How do I filter the results of a AR query without executing an additional query?
e.g.
u = User.where(name: "bob", age: [10, 20]) # 1st select query to db u.class # ActiveRecord::Relation tens = u.where(age: 10) # 2nd select query to db
I don't want the second query to call the db, but rather filter on the results retrieved in u (1st query).