Ruby on rails 按属性的子字符串(时间)对记录排序
我有此活动记录查询:Ruby on rails 按属性的子字符串(时间)对记录排序,ruby-on-rails,sorting,Ruby On Rails,Sorting,我有此活动记录查询: shop = Shop.find(12934) 然后我像这样从这家商店买了一系列产品 @product_templates = [] shop.products.each do |product| @product_templates.push(product.template) end 现在我有一组活动记录对象,如下所示: [ #<Product::Template id: 185549, name: "1:30pm", position: 0>,
shop = Shop.find(12934)
然后我像这样从这家商店买了一系列产品
@product_templates = []
shop.products.each do |product|
@product_templates.push(product.template)
end
现在我有一组活动记录对象,如下所示:
[
#<Product::Template id: 185549, name: "1:30pm", position: 0>,
#<Product::Template id: 185522, name: "11:30am", position: 1>,
#<Product::Template id: 185580, name: "7:00pm", position: 2>,
#<Product::Template id: 185556, name: "10:00am", position: 3>,
]
我想通过在名称中按时间对每个Product::Template进行排序来更新position属性,例如
10:00am、11:30am、1:30pm、7:00pm将是对象的顺序,因此10:00am对象将获得位置:0,7:00pm将获得位置:3等
我该怎么做?提前感谢您的时间尝试以下方法:
@product_templates.sort { |t1, t2| Time.strptime(t1, "%I:%M%P") <=> Time.strptime(t2, "%I:%M%P") }.each_with_index { |template, index| product.position = index }
我所做的是先对模板数组进行排序,然后根据数组索引更新位置。首先,在排序之前填充@product\u模板的方法不是一个好方法
@product_templates =
shop.products
.map(&:template)
.sort_by{|template| template.name.to_time}
谢谢你,伙计,我一整天都在发疯。已更改为使用to_time而不是time.strtime,但效果非常好