# Sorting by subsidiary class

**URL:** <https://www.ruby-forum.com/t/sorting-by-subsidiary-class/161033>\
**Category:** Rails\
**Created:** [February 22, 2009, 4:49pm UTC](https://www.ruby-forum.com/t/sorting-by-subsidiary-class/161033 "2009-02-22T16:49:45Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![DanC](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/77aa72/32.png) [@DanC](https://www.ruby-forum.com/u/DanC)\
**Post date:** [February 22, 2009, 4:49pm UTC](https://www.ruby-forum.com/t/sorting-by-subsidiary-class/161033/1 "2009-02-22T16:49:45Z")

</div>

Hi all,

My app contains categories, service and discounts.

A category has\_many :services  
A service belongs\_to :category and has\_one discount  
A discount belongs\_to :service

On each category show page I list all of the associated services, but  
would like to order them by some of the entries in the discount  
table.

i.e. in my categories controller

```
@category = Category.find(params[:id])
@services=Service.find(:all, :order => "XXXXXXX", :conditions =>

```

[‘category\_id = ?’, @category.id])

where XXXX relates to one of the columns in the discount table. The  
column gives the % discount available stored as an integer field.

Any ideas on best practice here,

I thought I could write a method into the Service.rb model file but  
although I can call the value easily I can’t order by the entry.

def reduction  
return discount.percentage  
end

All help appreciated.

Dan C

---

<div class="post-metadata">

**Author:** ![DanC](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/77aa72/32.png) [@DanC](https://www.ruby-forum.com/u/DanC)\
**Post date:** [February 23, 2009, 5:09am UTC](https://www.ruby-forum.com/t/sorting-by-subsidiary-class/161033/2 "2009-02-23T05:09:32Z")

</div>

> @category = Category.find(params[:id])  
> @services=Service.find(:all, :order =\> “XXXXXXX”, :conditions =\>  
> [‘category\_id = ?’, @category.id])

@category = Category.find(params[:id])  
@category.services.sort! { |x, y| x.reduction \<=\> y.reduction }

---

<div class="post-metadata">

**Author:** ![DanC](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/77aa72/32.png) [@DanC](https://www.ruby-forum.com/u/DanC)\
**Post date:** [February 23, 2009, 9:45am UTC](https://www.ruby-forum.com/t/sorting-by-subsidiary-class/161033/3 "2009-02-23T09:45:21Z")

</div>

On Feb 22, 3:48 pm, DanC [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> i.e. in my categories controller
> 
> ```
> @category = Category.find(params[:id])
> @services=Service.find(:all, :order => "XXXXXXX", :conditions =>
> 
> ```
> 
> [‘category\_id = ?’, @category.id])

If you join the discounts table you can just order by  
discounts.percentage

Fred
