Conditions when using include

Ok,

I have a sales_order table that I need to list. I need to be able to
filter this list of orders by their current route ( or status). Each
sales_order can have many histories associated with it. The most recent
histories associated with a sales_order defines it’s current route. The
histories table has a route_id which corresponds to the route name in
the routes table.

I need to include this current route in my sales_order listing. I have
accomplished this with the following in my controller:

@sales_orders = SalesOrder.find(:all, :include => :routes, :order =>
‘routes.id’)

This works, but the order by part of it doesn’t work at all. Items in
the Engineering route should be all together in the list, but they’re
not. I have yet to find a reason why this doesn’t work. I have been
all over the net and the Rails API and still haven’t found a workaround.

So, I’m trying now to filter the list based on current route. Here’s
the code I have for that:

if request.post?
rid = params[:route][:route_id]
@sales_orders = SalesOrder.find(:all, :include => :histories,
:conditions => [‘histories.route_id = ?’,rid])
end

This doesn’t work either. The log shows one sales_order with a
different status is being pulled from the db:

[4;35;1mHistory Load (0.000000)e[0m e[0mSELECT * FROM histories WHERE
(histories.sales_order_id = 771224) ORDER BY id desc LIMIT 1e[0m

[4;36;1mRoute Load (0.000000)e[0m e[0;1mSELECT * FROM routes WHERE
(routes.id = 29) e[0m

[4;35;1mHistory Load (0.016000)e[0m e[0mSELECT * FROM histories WHERE
(histories.sales_order_id = 771434) ORDER BY id desc LIMIT 1e[0m

[4;36;1mRoute Load (0.000000)e[0m e[0;1mSELECT * FROM routes WHERE
(routes.id = 29) e[0m

[4;35;1mHistory Load (0.000000)e[0m e[0mSELECT * FROM histories WHERE
(histories.sales_order_id = 771582) ORDER BY id desc LIMIT 1e[0m

[4;36;1mRoute Load (0.000000)e[0m e[0;1mSELECT * FROM routes WHERE
(routes.id = 13) e[0m

Why is that last one getting route_id 13? All of the others are getting
route_id 29, which is correct?

Any help that someone can give is much appreciated. I’ve been all over
the net and all over this forum trying to get either an :order or a
:conditions to work, and I can’t make either work.

Thanks,

Jason