# Sort on dates from has\_many?

**URL:** <https://www.ruby-forum.com/t/sort-on-dates-from-has-many/112067>\
**Category:** Rails\
**Created:** [August 14, 2007, 10:46pm UTC](https://www.ruby-forum.com/t/sort-on-dates-from-has-many/112067 "2007-08-14T22:46:07Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Wyatt\_Draggoo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/b2d939/32.png) [@Wyatt\_Draggoo](https://www.ruby-forum.com/u/Wyatt_Draggoo)\
**Post date:** [August 14, 2007, 10:46pm UTC](https://www.ruby-forum.com/t/sort-on-dates-from-has-many/112067/1 "2007-08-14T22:46:07Z")

</div>

Hey all,

First, still getting into Ruby/Rails, and am drinking from a firehose. A  
lot of good information on this list if you can get to it!

I have an Event model with many Showings. The Showings are simply dates  
that are related to the Event.

I’m trying to get the Events in the order of the first Showing date, and  
not have them repeat.

Right now, I have this in my index:

```
@allShowings = Showing.find(:all, :order => 'date')

@events = Array.new
@showings = Array.new
@shown = Hash.new

@allShowings.each do |showing|
  unless @shown.has_key?(showing.event_id)
    @events << Event.find_by_id(showing.event_id)
    @showings << showing
  end

  @shown[showing.event_id] = 1;
end

```

end

It works, but I need the same sorted data in other places. Should I have  
a private method that returns a sorted list of Events like this?

Is there some way I can use the Showing date order when I’m doing the  
Event.find?

Event.find(:all, :order =\> (magic pulling the order from Showings goes  
here))

Thanks,  
Wyatt

---

<div class="post-metadata">

**Author:** ![Wyatt\_Draggoo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/b2d939/32.png) [@Wyatt\_Draggoo](https://www.ruby-forum.com/u/Wyatt_Draggoo)\
**Post date:** [August 14, 2007, 11:35pm UTC](https://www.ruby-forum.com/t/sort-on-dates-from-has-many/112067/2 "2007-08-14T23:35:12Z")

</div>

in the Event model, you could say  
has\_many :showings, :order =\> ‘date’

then perhaps make a finder  
def self.find\_ordered  
Event.find(:all, :order =\> ‘showings.date’, :include =\> :showings)  
end

use in a controller:  
@ordered\_events = Event.find\_ordered

the “:order” clause in the model’s association macro isn’t necessary  
to make the custom finder, but it will help if you always want  
event.showings to default to date order

---

<div class="post-metadata">

**Author:** ![Wyatt\_Draggoo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/b2d939/32.png) [@Wyatt\_Draggoo](https://www.ruby-forum.com/u/Wyatt_Draggoo)\
**Post date:** [August 15, 2007, 4:14am UTC](https://www.ruby-forum.com/t/sort-on-dates-from-has-many/112067/3 "2007-08-15T04:14:29Z")

</div>

That’s exactly what I was looking for.

Thank you!
