ruby on rails - Preloading associations for a model with queries -


so, let's have users class, , fetch instance of user so:

@user = user.first 

and lets user has_many :posts, , post has_many :comments. want preload posts , comments associations use later. can achieved doing: activerecord::associations::preloader.new.preload(@user, {:posts => :comments}) want run few queries on model , it's preloaded associations. basically, want equivalent of user.where({:comments => {:post => {:topic => "math"}}).includes({:posts => :comments}).find(some_id). since i've loaded model once, don't want load again. there way of passing in clause preloader statement above in order create 1 big sql query instead of several smaller ones? i'm using postgres, , understanding, fewer queries in general means faster times.

use

@user = user.includes(posts: :comments).first 

then subsequent queries run on preloaded posts , comments or use cached version of query...


Comments