# Habtm order\_by

**URL:** <https://www.ruby-forum.com/t/habtm-order-by/120343>\
**Category:** Rails\
**Created:** [November 15, 2007, 11:12pm UTC](https://www.ruby-forum.com/t/habtm-order-by/120343 "2007-11-15T23:12:47Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![flamingsole](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/f19dbf/32.png) [@flamingsole](https://www.ruby-forum.com/u/flamingsole)\
**Post date:** [November 15, 2007, 11:12pm UTC](https://www.ruby-forum.com/t/habtm-order-by/120343/1 "2007-11-15T23:12:47Z")

</div>

Hello,

Is it possible to order a result set by one of the values in an habtm  
relationship? If so, how can this be done?

For example, I have a data set of providers.

@levels = Level.find(:all)  
@pages, providers = paginate(:providers, :conditions =\> [“last\_name LIKE  
?”, @initial+’%’], :order =\> “last\_name, first\_name”)  
@providers = providers.collect { |provider| provider }

In the model, providers has\_and\_belongs\_to\_many levels, and levels  
has\_and\_belongs\_to\_many providers. Is it possible, whether in the view  
or in the controller, to cause the query to sort itself by levels? So,  
it would display the providers associated within a given level, and then  
sort by whatever is in the controller.

Currently, the view is like this:

\<% if @pages %\>  
\<% for provider in @providers %\>  
(enter values for the provider in this area. I can get it to display  
values from the level by doing this:)  
\<% for level in provider.levels do %\>\<%= level.name.downcase %\>\<% end %\>  
\<% end %\>  
\<% end %\>

Any thoughts would be most appreciated. Thanks.  
Jonathan
