# Conditions when using include

**URL:** <https://www.ruby-forum.com/t/conditions-when-using-include/91198>\
**Category:** Rails\
**Created:** [April 5, 2007, 3:56pm UTC](https://www.ruby-forum.com/t/conditions-when-using-include/91198 "2007-04-05T15:56:00Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jason](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/dc4da7/32.png) [@jason](https://www.ruby-forum.com/u/jason)\
**Post date:** [April 5, 2007, 3:56pm UTC](https://www.ruby-forum.com/t/conditions-when-using-include/91198/1 "2007-04-05T15:56:00Z")

</div>

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
