I'm trying to order a find through a has_many association. I have a model called SalesOrder. Each sales order has things like amount, description, etc. I use the following to get the Sales Orders:
@sales_orders = SalesOrder.find(:all)
And I display them with:
<td><%= link_to sales_order.id.to_s, :action => 'show', :id => sales_order.id %></td> <td><%= sales_order.sold_to %></td> <td><%= sales_order.ship_to %></td> <td><%= (sales_order.rep.length < 1 ? " " : sales_order.rep) %></
<td><%= sales_order.description %></td> <td class="right_align"><%= sprintf("%#1.2f", sales_order.amount) %></
<td><%= sales_order.ship_date.strftime('%m/%d/%y') %></td> <td><%= sales_order.latest_history.nil? ? " " : sales_order.latest_history.route.name %></td>
The problem is that this list is not in the order that I need it to be. I can order it by any column in the sales_orders table, but I need to order it by latest_history.route.name I don't know how to order a query based on another table's column. Is this even possible? Or is there another way to accomplish the same result? My model definitions are below:
class SalesOrder < ActiveRecord::Base has_many :histories has_one :latest_history, :class_name => "History", :order => "id desc" end
class History < ActiveRecord::Base belongs_to :route belongs_to :sales_order end
class Route < ActiveRecord::Base has_many :histories has_and_belongs_to_many :users
end
Thanks!