Forum: Ruby on Rails Alternative to STI with eager loading

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8f23570fbde6277118fcd088a675f61a?d=identicon&s=25 Joshua Kahn (jkahn)
on 2007-03-09 16:15
In order to implement inheritance (STI was not ideal), I have
implemented a solution similar to what is described in this post:
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
C64e63b70be7dfed8b0742540b8b27e5?d=identicon&s=25 Mark Reginald James (Guest)
on 2007-03-09 17:38
(Received via mailing list)
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.
This topic is locked and can not be replied to.