# Alternative to STI with eager loading

**URL:** <https://www.ruby-forum.com/t/alternative-to-sti-with-eager-loading/88310>\
**Category:** Rails\
**Created:** [March 9, 2007, 4:15pm UTC](https://www.ruby-forum.com/t/alternative-to-sti-with-eager-loading/88310 "2007-03-09T16:15:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jkahn](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/53a042/32.png) [@jkahn](https://www.ruby-forum.com/u/jkahn)\
**Post date:** [March 9, 2007, 4:15pm UTC](https://www.ruby-forum.com/t/alternative-to-sti-with-eager-loading/88310/1 "2007-03-09T16:15:22Z")

</div>

In order to implement inheritance (STI was not ideal), I have  
implemented a solution similar to what is described in this post:  
[Any good alternative to single-table-inheritance? - Rails - Ruby-Forum](http://www.ruby-forum.com/topic/73822#108686). I have one model that  
acts as a parent class with shared attributes, two child models with  
the distinct attributes for those classes, and a module that contains  
shared functionality for the child models. In the DB, there is one table  
per class with foreign keys in the “child” tables the parent.

The issue arises in creating associations with other models when it is  
necessary to provide conditions on the association, for example:

has\_many :foos, :conditions =\> “foo\_metadata.created\_at \< #{Time.now}”,  
:order =\> ‘foo.bar DESC, foo\_metadata.baz’

I can use eager loading to include the foo\_metadata relationship,  
however, this becomes cumbersome and difficult to manage throughout  
the application. Is there an alternative solution to this problem? Can  
I require eager loading of foo\_metadata on all foo finds/conditions?

Thanks,  
Josh

---

<div class="post-metadata">

**Author:** ![jkahn](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/53a042/32.png) [@jkahn](https://www.ruby-forum.com/u/jkahn)\
**Post date:** [March 9, 2007, 5:38pm UTC](https://www.ruby-forum.com/t/alternative-to-sti-with-eager-loading/88310/2 "2007-03-09T17:38:01Z")

</div>

Joshua Kahn wrote:

> has\_many :foos, :conditions =\> “foo\_metadata.created\_at \< #{Time.now}”,  
> :order =\> ‘foo.bar DESC, foo\_metadata.baz’
> 
> I can use eager loading to include the foo\_metadata relationship,  
> however, this becomes cumbersome and difficult to manage throughout  
> the application. Is there an alternative solution to this problem? Can  
> I require eager loading of foo\_metadata on all foo finds/conditions?

You can add an :include =\> :foo\_metadata option to the has\_many  
declaration. Any includes you use in a find with be automatically  
merged with this.

Unfortunately, use of eager loading does limit how find can be  
used in some circumstances, and is wasteful if you’re only using  
the fields in the condition. has\_many does not however support  
the :joins option.

–  
We develop, watch us RoR, in numbers too big to ignore.
