How to prevent query being executed for each row in list

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.

On 9 May 2010 17:26, Edwin [email protected] 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:

I have just started using rails

Welcome! :slight_smile:
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.