Skip to content

Instantly share code, notes, and snippets.

@maxcal
Last active December 29, 2022 14:55
Show Gist options
  • Save maxcal/ab62b800447fe0cb9914f519ab1e7fd3 to your computer and use it in GitHub Desktop.
Save maxcal/ab62b800447fe0cb9914f519ab1e7fd3 to your computer and use it in GitHub Desktop.
User Exists? (1.3ms) SELECT 1 AS one FROM "users" WHERE "users"."username" = $1 LIMIT $2 [["username", "michael"], ["LIMIT", 1]]
User Create (0.5ms) INSERT INTO "users" ("username", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["username", "michael"], ["created_at", "2022-12-29 14:51:02.384023"], ["updated_at", "2022-12-29 14:51:02.384023"]]
User Exists? (0.4ms) SELECT 1 AS one FROM "users" WHERE "users"."username" = $1 LIMIT $2 [["username", "lebron"], ["LIMIT", 1]]
User Create (0.2ms) INSERT INTO "users" ("username", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["username", "lebron"], ["created_at", "2022-12-29 14:51:02.386506"], ["updated_at", "2022-12-29 14:51:02.386506"]]
User Exists? (0.3ms) SELECT 1 AS one FROM "users" WHERE "users"."username" = $1 LIMIT $2 [["username", "michael"], ["LIMIT", 1]]
TRANSACTION (0.3ms) ROLLBACK
class User < ApplicationRecord
validates_uniqueness_of :username
end
require "test_helper"
class UserTest < ActiveSupport::TestCase
test "inserting users in a transaction" do
assert_difference ->{ User.count }, 0 do
begin
ActiveRecord::Base.transaction do
User.create!(username: "michael") # short-cut for `new(...).save!`
User.create!(username: "lebron")
User.create!(username: "michael") # not unique error
end
rescue ActiveRecord::RecordInvalid
nil
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment