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
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
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
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.
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.
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 Biedenharn http://agileconsultingllc.com