luke
luke

Reputation: 1578

Sort records by substring (time) of attribute

I have this active record query:

shop = Shop.find(12934)

I then go and get a collection of products from this shop like so

@product_templates = []

shop.products.each do |product|
  @product_templates.push(product.template)
end

So now I have an array of active record objects which look like this:

[
 #<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>,
]

I want to update the position attribute by ordering each of these Product::Template by the time in the name e.g.

10:00am, 11:30am, 1:30pm, 7:00pm would be the order of the objects so the 10:00am object would get position: 0, 7:00pm would get position:3 etc.

How would I do this? Thanks for your time in advance

Upvotes: 0

Views: 33

Answers (2)

sawa
sawa

Reputation: 168179

First of all, your way of filling @product_templates before sort is not a good way.

@product_templates =
shop.products
.map(&:template)
.sort_by{|template| template.name.to_time}

Upvotes: 0

kasperite
kasperite

Reputation: 2478

try this:

@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 }

What I did there was sorting your template array first, then updating position based on array index.

Upvotes: 1

Related Questions