Skip to content

Instantly share code, notes, and snippets.

@dabit
Last active August 29, 2015 13:56
Show Gist options
  • Save dabit/8855054 to your computer and use it in GitHub Desktop.
Save dabit/8855054 to your computer and use it in GitHub Desktop.
ActiveRecord Optimistic Locking
require 'active_record'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :orders do |t|
t.integer :total
t.string :lock_version
end
end
class Order < ActiveRecord::Base ; end
Order.create
object_1 = Order.find(1)
object_2 = Order.find(1)
object_1.total = 100
object_1.save # Succeeds!
object_2.total = 200
object_2.save # Raises ActiveRecord::StaleObjectError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment