views:

22

answers:

1

Hi,

Not sure this could fall in performance section as well as model/database section, so here goes....

Let's say I have 3 models:

Movie {
has_one :interest, :as => :resource
}
Song {
has_one :interest, :as => :resource
}
Story {
has_one :interest, :as => :resource
}

and ...

Interest {
belongs_to :resource, :polymorphic => true
}

Now, if I need a list of all interests for all movies, and I want to show also the date those Movies objects were created (to say how old they were), then I use the lookup on resource_type attribute and then @some_interest.resource.created_at.

The problem with this is if I have 100 movie interests, then I will get 101 queries right ? So linear degradation. I tried using :include => [:resource] in my query call, but it says cannot use include in polymorphic associations.

How can I either eager load or optimize this problem to avoid this severe degradation ??

Any help would be greatly appreciated !!

A: 

If you are using searchlogic, there is a special syntax to deal with polymorphic relationships that may help. You can search on the has side of the relationship by specifying the name of the related class suffixed with type.

E.g. given your models, you ought to be able to do something like this to get movies created in the last 90 days:

Interest.resource_movie_type_created_at_gt(Time.now-90.days)

Searchlogic sets up the join on the related model for you, which should allay performance concerns.

Of course you can always write your own SQL using the find_by_sql method.

PS. one very helpful trick is to turn on logging in the Rails console while writing searches. This allows you to see the SQL generated right in the console without having to dig through the logs.

zetetic