Basic Active Record find question

Given the following simple model:

A page has many sections
A section has many entries
Each entry has a time_stamp

I can easily find all the entries of a section sorted by time_stamp:

section.entries.find
(:all, :order => “time_stamp”)

But what if I need all the entries of a page sorted by time_stamp?

One thought was to search across all entries and use Array.include? to constrain the entries to the sections of a page:

section_ids = []
page.sections.each do |section|
section_ids << section.id
end
Section.find
(:all, :conditions => ["?.include? section_id", section_ids], :order => “time_stamp”)

I can’t get this to work because I can’t find a way to escape the second question mark.

But perhaps there is a better way of doing this?

Cheers!

Try this:

section_ids = page.sections.map {|s| s.id}

Entries.find (:all, :conditions => “section_id in (#{section_ids * ‘,’})”, :order => “time_stamp”)

Aaron

Thank you.

For my fellow Ruby newbies, section_ids * ‘,’ expands to a string with each element of the section_ids array and a ‘,’ in between: “1,2,3”
#{} allows substituting the value of any Ruby code into a string. The net effect is a condition such as ‘section_id in (1,2,3)’

Cheers!

Simpler:
Entries.find(:all, :conditions => [‘section_id in (?)’, section_ids]

Simplest:
page.sections.find(:all, :include => :entries)

jeremy

Simpler:
Entries.find(:all, :conditions => [‘section_id in (?)’, section_ids]

This makes sense and it works well.

Simplest:
page.sections.find(:all, :include => :entries)

This won’t work in this case because I need the entries sorted by time_stamp across all sections, so I’d have to iterate through the returned sections, store all the entries and then sort them myself. Doing an Entry.find along with :order makes the database do the sorting for me.

Cheers!