ruby - Sorting elements in DataMapper -
i have database, , need sort whole table length, 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/?' 5.times val = rand(100) item.create(length: val) end item.update(item.sort_by { |_key, value| value }) redirect to('/items') end
how can perform correctly, database update sorted length
elements? thank you.
item.sort_by(&:length)
above code 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 >
Comments
Post a Comment