# How to prevent query being executed for each row in list

**URL:** <https://www.ruby-forum.com/t/how-to-prevent-query-being-executed-for-each-row-in-list/188324>\
**Category:** Rails\
**Created:** [May 10, 2010, 10:56am UTC](https://www.ruby-forum.com/t/how-to-prevent-query-being-executed-for-each-row-in-list/188324 "2010-05-10T10:56:01Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![edwin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/73ab20/32.png) [@edwin](https://www.ruby-forum.com/u/edwin)\
**Post date:** [May 10, 2010, 10:56am UTC](https://www.ruby-forum.com/t/how-to-prevent-query-being-executed-for-each-row-in-list/188324/1 "2010-05-10T10:56:01Z")

</div>

Hello,

I have just started using rails and I am wondering how I can prevent a  
query being executed for each row in my list view.

I have 2 models: OrganizationType and Organization which has a one-to-  
many relationship through association in the models.

In the controller when Organization.all is being executed I see that  
select statement is created that joins both tables as expected.  
However in the list I output OrganizationType’s description with “\<%=h  
organization.organization\_type.description %\>” and this seems to  
execute another query for the OrganizationType. I am assuming this is  
because of the organization\_type method that has been added by rails  
in organization due to the association.

How can I output the OrganizationType’s description from the  
@organizations variable without a query being executed for each row in  
the list?

Thanks, Edwin.

---

<div class="post-metadata">

**Author:** ![edwin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/73ab20/32.png) [@edwin](https://www.ruby-forum.com/u/edwin)\
**Post date:** [May 10, 2010, 11:24am UTC](https://www.ruby-forum.com/t/how-to-prevent-query-being-executed-for-each-row-in-list/188324/2 "2010-05-10T11:24:43Z")

</div>

On 9 May 2010 17:26, Edwin [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> How can I output the OrganizationType’s description from the  
> @organizations variable without a query being executed for each row in  
> the list?

You can use the “:include” option of AR to eager-load relationships:

> **[ActiveRecord::Base](https://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002263)**
>
> Active Record Active Record objects don't specify their attributes directly, but rather infer them from the table definition with which they're linked.

> I have just started using rails

Welcome! 🙂  
I’d suggest not to worry too much (at this stage) about which queries  
are being executed when. While learning, I’d just focus on the  
higher-level operations of the framework.
