Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'bundler/inline'
gemfile(true) do
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'sqlite3'
gem 'uuidtools'
end
require 'active_record'
require 'minitest/autorun'
require 'logger'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table 'tokens', id: :binary, limit: 16, force: true
create_table 'users', force: true
create_table 'token_users', force: true do |t|
t.integer 'user_id'
t.binary 'token_id', limit: 16, null: false
end
end
class UuidType < ActiveRecord::Type::Binary
def serialize(value)
super(cast_to_uuid(value)&.raw)
end
def deserialize(value)
cast_to_uuid(super(value)).to_s
end
def cast_value(value)
cast_to_uuid(value).to_s
end
private
def cast_to_uuid(value)
return if value.nil?
case value.size
when 16 then UUIDTools::UUID.parse_raw(value)
when 36 then UUIDTools::UUID.parse(value)
end
end
end
class User < ActiveRecord::Base
end
class Token < ActiveRecord::Base
attribute :id, UuidType.new, default: SecureRandom.uuid
has_many :token_users
has_many :users, through: :token_users
end
class TokenUser < ActiveRecord::Base
attribute :token_id, UuidType.new
belongs_to :user
belongs_to :token
end
class IssueTest < Minitest::Test
def test_association_with_uuid
token = Token.create!
token.users << User.create!
assert_equal 1, token.reload.token_users.count
assert_equal 1, token.reload.users.count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment