Eager loading wierdness

Consider this problem.

I have an Item that has_many Features

I want to find all Items with a Feature name of ‘foo’.

Normally you would do this…

@items = Item.find(:all, :conditions=>[“features.name = ?”, ‘foo’],
:include=>:features)

This all works fine and dandy except for this problem.

If you do this…

<% for item in @items %>
<%= item.features.map {|x| x.name}.to_sentence %>
<% end %>

you only get the features listed that match the search criteria. If the
item object has 10 different features associated and you search for one,
the .features association only returns the one you searched on instead
of the entire list of associated objects.

Anyone know of a way to structure the search to return them all short of
reloading each object?

BTW: Rails 1.1.4

_Kevin
www.sciwerks.com

On 7-Aug-06, at 7:33 AM, Kevin O. wrote:

item object has 10 different features associated and you search for
one,
the .features association only returns the one you searched on instead
of the entire list of associated objects.

Anyone know of a way to structure the search to return them all
short of
reloading each object?

Hey Kevin,

you could reduce db hits like this (off the top of my head, not tested):

item_ids = Item.find(:all, :select => ‘distinct items.id’,
:joins => ‘inner join features on features.item_id = items.id’,
:conditions => [‘features.name = ?’, ‘foo’]
)

@items = Item.find(:all,
:conditions => ['items.id in (?), item_ids.collect(&:id)],
:include => :features
)

HTH,
Trevor

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs