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.
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 >