0

I have a database, and I need to sort the whole table by the length, however I've got stack on it.

require 'dm-core'
require 'dm-migrations'
require 'sinatra/reloader'

DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/development.db")

class Item
  include DataMapper::Resource

  property :id, Serial
  property :length, Integer
end

...

DataMapper.finalize

post '/items/sort/?' do
5.times do
    val = rand(100)
    Item.create(length: val)
  end

  Item.update(Item.sort_by { |_key, value| value })
  redirect to('/items')
end

How can I perform it correctly, so as my database will update with sorted by length elements? Thank you.

NLis
  • 53
  • 2
  • 8
  • what would you like to do? what is the meaning of `Item.update(Item.sort_by { |_key, value| value })` statement? – marmeladze Apr 06 '17 at 11:31
  • Having filled a database with id-length pairs, now I want to sort this table by lenght. For instance, having `@id=1, @length=3` , `@id=2, @length=2` , `@id=3, @length=4` in my table, I want to have a `@id=2, @length=2`, `@id=1, @length=3`, `@id=3, length=4`, so just sort them by `length` parameter. That statement means that database should update itself with sorted one (assume it represents everything in a `id=>length` hash). – NLis Apr 06 '17 at 11:43

1 Answers1

0
Item.sort_by(&:length)

above code will help you to achieve desired result.

2.3.1 :001 > require './app.rb'
 => true 
2.3.1 :002 > Item.all
 => [#<Item @id=1 @length=21>, #<Item @id=2 @length=85>, #<Item @id=3 @length=41>, #<Item @id=4 @length=71>, #<Item @id=5 @length=71>] 
2.3.1 :003 > Item.sort_by(&:length)
 => [#<Item @id=1 @length=21>, #<Item @id=3 @length=41>, #<Item @id=4 @length=71>, #<Item @id=5 @length=71>, #<Item @id=2 @length=85>] 
2.3.1 :004 > 
marmeladze
  • 6,468
  • 3
  • 24
  • 45