Forum: Ruby on Rails Maintaining order when I call Video.find("3", "1", "2")

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Pat M. (Guest)
on 2007-02-06 01:20
(Received via mailing list)
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
Brad E. (Guest)
on 2007-02-06 01:27
(Received via mailing list)
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
Daniel -. (Guest)
on 2007-02-06 01:41
(Received via mailing list)
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.
Rob B. (Guest)
on 2007-02-06 01:57
(Received via mailing list)
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
This topic is locked and can not be replied to.