# Eager loading of association extensions

**URL:** <https://www.ruby-forum.com/t/eager-loading-of-association-extensions/137047>\
**Category:** Rails\
**Created:** [May 8, 2008, 3:57pm UTC](https://www.ruby-forum.com/t/eager-loading-of-association-extensions/137047 "2008-05-08T15:57:13Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![yuleven](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/y/c89c15/32.png) [@yuleven](https://www.ruby-forum.com/u/yuleven)\
**Post date:** [May 8, 2008, 3:57pm UTC](https://www.ruby-forum.com/t/eager-loading-of-association-extensions/137047/1 "2008-05-08T15:57:13Z")

</div>

Hello all,

Is it possible to do eager loading of association extensions?

That is, the following code produces one SQL query:

```
  cat = ProductCategory.find(:first, :include => :pricing_rules)
  cat.pricing_rules

```

But if in ProductCategory I have an association extension like this:

has\_many :pricing\_rules do  
def applicable()  
find(:all).select(&:applicable?)  
end  
end

the code

```
    cat = ProductCategory.find(:first, :include => :pricing_rules)
    cat.pricing_rules.applicable

```

will produce 2 queries anyway, :include is useless here.

I see no other way that to add another association:

has\_many :applicable\_pricing\_rules :conditions =\> ‘appliccable is true’

and then use it:

cat = ProductCategory.find(:first, :include =\>  
:applicable\_pricing\_rules)  
cat.applicable\_pricing\_rules

But maybe there’s a way to eagerly load an association extension?

–  
Best regards,  
Yuri L.

---

<div class="post-metadata">

**Author:** ![yuleven](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/y/c89c15/32.png) [@yuleven](https://www.ruby-forum.com/u/yuleven)\
**Post date:** [May 8, 2008, 4:58pm UTC](https://www.ruby-forum.com/t/eager-loading-of-association-extensions/137047/2 "2008-05-08T16:58:16Z")

</div>

On May 8, 2:55 pm, “Yuri L.” [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> I see no other way that to add another association:
> 
> has\_many :applicable\_pricing\_rules :conditions =\> ‘appliccable is true’
> 
> and then use it:
> 
> cat = ProductCategory.find(:first, :include =\> :applicable\_pricing\_rules)  
> cat.applicable\_pricing\_rules
> 
> But maybe there’s a way to eagerly load an association extension?

There is no way. The extra association route would also be more  
efficient because you only query the database for the relevant records  
rather than getting all of them and then throwing away some.  
But you could rewrite your association so that it uses pricing\_rules,  
ie

def applicable  
load\_target.select(&:applicable?)  
end

Fred
