Search code examples
rubyruby-on-rails-4eager-loading

If I eager load associated child records, then that means future WHERE retrievals won't dig through database again?


Just trying to understand... if at the start of some method I eager load a record and its associated children like this:

@object = Object.include(:children).where(email:"test@example.com").first

Then does that mean that if later I have to look through that object's children this will not generate more database queries?

I.e.,

@found_child = @object.children.where(type_of_child:"this type").first

Solution

  • Unfortunately not - using ActiveRecord::Relation methods such as where will query the database again.

    You could however filter the data without any further queries, using the standard Array / Enumerable methods:

    @object.children.detect {|child| child.type_of_child == "this type"}