Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

erickrause commented Sep 13, 2012

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
You can’t perform that action at this time.