Maintaining order when I call Video.find("3", "1", "2")


#1

If I call Video.find(“3”, “1”, “2”), it’ll give me all the videos but
the orders will be with ids 1, 2, and 3. I want to maintain the order
that I pass it in. Is there a quick easy way to do that? Either
sorting in the db or with Ruby.

Pat


#2

On Feb 5, 2007, at 5:17 PM, Pat M. wrote:

If I call Video.find(“3”, “1”, “2”), it’ll give me all the videos but
the orders will be with ids 1, 2, and 3. I want to maintain the order
that I pass it in. Is there a quick easy way to do that? Either
sorting in the db or with Ruby.

I think your best bet is to separate them out into separate SQL
statements. The connection adapter is translating that into something
like:

SELECT … FROM videos WHERE id IN (3,1,2);

The result set from the database will most likely come out in DB-
natural order, which probably works out to PK order. In any case, it
is database dependent and I can’t think of an easy way to get the
result set in a particular order. You can always do

ids.map {|id| Video.find(id)}

but of course it multiplies the number of queries by n.

Brad


#3

On 2/6/07, Pat M. removed_email_address@domain.invalid wrote:

If I call Video.find(“3”, “1”, “2”), it’ll give me all the videos but
the orders will be with ids 1, 2, and 3. I want to maintain the order
that I pass it in. Is there a quick easy way to do that? Either
sorting in the db or with Ruby.

Pat

For a quick stab

video_ids = [3,1,2]
videos_temp = Video.find( *video_ids )
videos = video_ids.map{ |vid| videos_temp.detect{ |video| video.id ==
vid }
}

Whoa that’s ugly.


#4

On Feb 5, 2007, at 6:40 PM, Daniel N wrote:

For a quick stab

video_ids = [3,1,2]
videos_temp = Video.find( *video_ids )
videos = video_ids.map{ |vid| videos_temp.detect{ |video| video.id
== vid } }

Whoa that’s ugly.

Hopefully this isn’t:

ids = [36, 27, 35]
=> [36, 27, 35]

products = Product.find ids
=> […stuff…]

products.size
=> 3

products.map(&:id)
=> [27, 35, 36]

products.sort_by {|p| ids.index(p.id)}.map(&:id)
=> [36, 27, 35]

ids
=> [36, 27, 35]

-Rob

Rob B. http://agileconsultingllc.com
removed_email_address@domain.invalid