Rails组合了4个数组,并通过“created_at”对结果数组进行排序

时间:2021-05-24 12:15:48

So I am trying to combine 4 arrays of different items and then sort those arrays by the column "created_at" as in newest first. So the resulting array should be an array of all those items sorted so that the newest item is the first no matter what type they are. I can sort it so that the newest item but it sorts through each type of item and then start sorting the other type.

所以我试图组合4个不同项目的数组,然后按照最新的第一个列“created_at”对这些数组进行排序。因此,生成的数组应该是所有那些排序的项目的数组,以便最新的项目是第一个,无论它们是什么类型。我可以对它进行排序以便最新的项目,但它会对每种类型的项目进行排序,然后开始对其他类型进行排序。

Example: the types are shirts and pants. I upload a shirt at 10:00pm and then a pant at 10:15pm and then again a shirt at 10:30pm. The array should be like (shirt(10:30), pant(10:15), shirt(10:00)) but instead I get a (shirt(10:00), shirt(10:30), pant(10:15))

示例:类型是衬衫和裤子。我在晚上10点上传一件衬衫,然后在晚上10点15分再上裤子,然后在晚上10:30又上一件衬衫。阵列应该像(衬衫(10:30),裤子(10:15),衬衫(10:00))而是我得到(衬衫(10:00),衬衫(10:30),裤子(10) :15))

Here is my code:

这是我的代码:

@tops = Top.first(15)
@bottoms = Bottom.first(15)
@footwears = Footwear.first(15)
@accs = Accessory.first(15)

@tempItems = []
@temp = []
@temp = @tempItems + @tops 
@temp = @temp + @bottoms 
@temp = @temp + @footwears 
@temp = @temp + @accs

@temp.sort_by{ |temp| - temp.created_at.to_i}
@itemss = @temp.first(15)

2 个解决方案

#1


2  

You need to assign the sorted array back to @temp

您需要将已排序的数组分配回@temp

...

@temp =  @temp.sort_by{ |temp| - temp.created_at.to_i}

#2


0  

You can reduce the confusion by getting rid of unnecessary assignment code:

您可以通过删除不必要的分配代码来减少混淆:

fifteen= [Top, Bottom, FootWear, Accessory].
  flat_map{ |c| c.first(15) }.
  sort_by{ |e| -e.created_at.to_i }.
  first(15)

#1


2  

You need to assign the sorted array back to @temp

您需要将已排序的数组分配回@temp

...

@temp =  @temp.sort_by{ |temp| - temp.created_at.to_i}

#2


0  

You can reduce the confusion by getting rid of unnecessary assignment code:

您可以通过删除不必要的分配代码来减少混淆:

fifteen= [Top, Bottom, FootWear, Accessory].
  flat_map{ |c| c.first(15) }.
  sort_by{ |e| -e.created_at.to_i }.
  first(15)