Created
July 17, 2019 19:53
-
-
Save neves/b5dfbbd27fb9bc05da4954bd53a4917a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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