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).
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 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With