0

I have next ids - video_ids: [1, 8, 2, 8, 3, 8]. So, each second record must be with id 8. When I make Video.where(id: [1, 8, 2, 8, 3, 8]).ids I have `[1, 8, 2, 3, 4]. So, active record find record with id 8 only one.

I would like after Video.where(id: [1, 8, 2, 8, 3, 8]) have => [<Video id: 1>, <Video id: 8>, <Video id: 2>, <Video id: 8>, <Video id: 3>, <Video id: 8>]

What can be done to do this?

  • 1
    Do you need a Video::ActiveRecord_Relation or an Array? – Sebastián Palma Mar 30 '21 at 16:11
  • Video::ActiveRecord_Relation – Volodymyr Babiy Mar 30 '21 at 16:28
  • `Video.where(id: [1, 8, 2, 8, 3, 8])` translates to `WHERE videos.id IN (1, 8, 2, 8, 3, 8)` in SQL. It does not in ANY way give you the records in that specific order or cause duplicates in any db I know of. The order depends entirely on the order clause (or the dbs default order). – max Mar 30 '21 at 20:48
  • I think the problem is not the order, but the total of records that's not the same as the input for the IN clause @max. – Sebastián Palma Mar 30 '21 at 20:52
  • @SebastianPalma I think the problem is either completely unrealistic expectations or an X&Y question. If you want to pull records in a specific order like that you would need to use `ORDER BY FIELD(id, 1, 8, 2, 8, 3, 8)` on MySQL or a case statement in Postgres. https://stackoverflow.com/questions/8322849/mysql-order-by-specific-id-values https://stackoverflow.com/questions/1309624/simulating-mysqls-order-by-field-in-postgresql – max Mar 30 '21 at 20:56

2 Answers2

0

Edit: OP asked for an activerecord object so this woudn't work for him

You could map the video_ids array with the videos found, as ActiveRecord will return only one record per id.

def video_playlist(ids)
  videos = Video.where(id: ids)
  ids.map { |id| videos.detect { |video| video.id == id } }
end

and use the method

video_playlist(video_ids)
RHFS
  • 356
  • 2
  • 9
0

It is not possible to fetch duplicate records in an ActiveRecord::Relation object. If you know only the odd records are going to have variable ids and even records are always going to have a fix id, there is no need to fetch the fix id records along with other records. You can simply fetch Video.where(id: [1, 2, 3]) together and fetch Video.find(8) in a separate query and write your logic based on this.

Sachin Singh
  • 993
  • 8
  • 16