# Active Record: Eager Loading (syntax question)

**URL:** <https://discuss.rubyonrails.org/t/active-record-eager-loading-syntax-question/69225>\
**Category:** rubyonrails-talk\
**Created:** [July 2, 2014, 12:37pm UTC](https://discuss.rubyonrails.org/t/active-record-eager-loading-syntax-question/69225 "2014-07-02T12:37:55Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![11155](https://avatars.discourse-cdn.com/v4/letter/1/d26b3c/32.png) [@11155](https://discuss.rubyonrails.org/u/11155)\
**Post date:** [July 2, 2014, 12:37pm UTC](https://discuss.rubyonrails.org/t/active-record-eager-loading-syntax-question/69225/1 "2014-07-02T12:37:55Z")

</div>

Let's have model :parents and :children, where one parent can have many children, and that I want to do something like this:

plist=Parent.joins(:children).select('\*').where("parents.id=children.parent\_id and children.cfield=#{...}")

plist.each { |p| do\_something\_with(p,p.children) }

Now I learned from [Active Record Query Interface — Ruby on Rails Guides](http://guides.rubyonrails.org/active_record_querying.html) , that this is inefficient, due to the SELECT statements generated inside the block, and that I should do "eager loading" instead. From my understanding of the tutorial, I should replace 'joins' by 'includes':

plist=Parent.includes(:children).select('\*').where("parents.id=children.parent\_id and children.cfield=#{...}")

However, this raises the exception that there would be no column "children.cfield".

It seems that with 'includes', we can only query based on values of the Parent table.

Is this correct?

---

<div class="post-metadata">

**Author:** ![Frederick\_Cheung](https://sea2.discourse-cdn.com/rubyonrails/user_avatar/discuss.rubyonrails.org/frederick_cheung/32/3901_2.png) [@Frederick\_Cheung](https://discuss.rubyonrails.org/u/Frederick_Cheung)\
**Post date:** [July 2, 2014, 2:37pm UTC](https://discuss.rubyonrails.org/t/active-record-eager-loading-syntax-question/69225/2 "2014-07-02T14:37:44Z")

</div>

In rails 4.1 (or possibly 4.0) and later you must use references if you are adding conditions on one of the joined columns, ie

Parent.includes(:children).references(:children)

So that rails knows it must use the joins based eager loading strategy (rails used to try and guess this for you but this was rather error-prone). You also don’t need the select(‘\*’)

Fred
