Skip to content

Instantly share code, notes, and snippets.

@bsimpson
Created September 13, 2012 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bsimpson/3716869 to your computer and use it in GitHub Desktop.
Save bsimpson/3716869 to your computer and use it in GitHub Desktop.
Validating within a Transaction
# == Schema Information
# bar :integer
class Foo < ActiveRecord::Base
validates_uniqueness_of :bar
end
a=Foo.new(bar: 1)
a.valid? # => true
b=Foo.new(bar: 1)
b.valid? # => true
a.save # => #<Foo id: 1, bar: 1>
b.valid? # => false
b.errors # => {:bar=>["has already been taken"]}
# Now with a transaction
a=Foo.new(bar: 2)
b=Foo.new(bar: 2)
ActiveRecord::Base.transaction do
a.save # validates here and INSERTS into local transaction
sleep 10
# commits here
end # => #<Foo id: 3, bar: 2>
# In a separate process within 10 seconds of issuing previous command
b.save # => #<Foo id: 4, bar: 2>
a.valid? # => false
a.errors # => {:bar=>["has already been taken"]}
b.valid? # => false
b.errors # => {:bar=>["has already been taken"]}
@erickrause
Copy link

ActiveRecord::Base.transaction do
Account.create!(name: "foo", plan: SubscriptionPlan.find(1))
sleep 30
end

Run in two consoles at the same time. reproduces

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment