Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering on activerecord relation without additional sql query?

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).

like image 844
Derek Avatar asked Oct 23 '13 18:10

Derek


1 Answers

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 
like image 189
tihom Avatar answered Oct 12 '22 01:10

tihom