Forum: Ruby on Rails eager loading optimization

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.
Richard S. (Guest)
on 2008-11-16 00:18
I have a phrase model, a definition model, and a children model
a phrase has many definitions, a definition has many children

currently when i am doing a find i have an include that looks like

Phrase.find(:all,:include => [{:definitions => :children}] , :conditions
=> 'foo')

but for the most part I only want the first definition, and its
associated children. The loading of all of the additional definitions
and their associated children is killing my site load time (but not more
than eliminating the :include all together).

Is there a way to get only the first definition under an associated
phrase ( the definitions are ordered by rank) without having to write my
own SQL ??

Rails 2.1.0 and Ruby 1.8.6
Mark Reginald J. (Guest)
on 2008-11-16 01:36
(Received via mailing list)
Richard S. wrote:
> and their associated children is killing my site load time (but not more
> than eliminating the :include all together).
>
> Is there a way to get only the first definition under an associated
> phrase ( the definitions are ordered by rank) without having to write my
> own SQL ??
>
> Rails 2.1.0 and Ruby 1.8.6

Tricky, but investigate something like:

class Phrase < ActiveRecord::Base
   has_one :top_ranked_definition, :class_name => 'Definition',
           :conditions => <<-END
     definitions.rank =
     (select max(rank) from definitions where phrase_id = phrases.id)
   END

Phrase.find :all, :include => {:top_ranked_definition => :children},
                   :conditions => 'foo'

--
Rails Wheels - Find Plugins, List & Sell Plugins -
http://railswheels.com
This topic is locked and can not be replied to.