Skip to content

Instantly share code, notes, and snippets.

@neves
Created July 17, 2019 19:53
Show Gist options
  • Save neves/b5dfbbd27fb9bc05da4954bd53a4917a to your computer and use it in GitHub Desktop.
Save neves/b5dfbbd27fb9bc05da4954bd53a4917a to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require 'sqlite3'
require 'active_record'
require 'ap'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Schema.define do
create_table :todos do |t|
t.string :label
t.integer :position
end
end
ActiveRecord::Base.logger = Logger.new(STDOUT)
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
class Todo < ApplicationRecord; end
Todo.create! label: 'Green', position: 0
Todo.create! label: 'Blue', position: 1
Todo.create! label: 'Red', position: 2
todos = Todo.order(:position).to_a
todos_new_order = todos.rotate(-1)
todos_new_order.each_with_index { |todo, i| todo.position = i }
todos_new_order.map(&:save)
# Result: Red, Green, Blue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment