Created
September 13, 2012 19:14
-
-
Save bsimpson/3716869 to your computer and use it in GitHub Desktop.
Validating within a Transaction
This file contains 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
# == 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"]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ActiveRecord::Base.transaction do
Account.create!(name: "foo", plan: SubscriptionPlan.find(1))
sleep 30
end
Run in two consoles at the same time. reproduces