I have a model with UUIDs stored in BINARY(16) field in a MySQL table. I would like to be able to transparently convert hexadecimal uuid into binary for the setter method and back when I use the getter method.
what is the 'right' way to proceed?
You override the setter and getter:
class User < ActiveRecord::Base
def uuid=(value)
@uuid = write_attribute(:uuid, value.scan(/../).map {|n| n.to_i(16)}.pack("C*"))
end
def uuid
@uuid ||= read_attribute(:uuid).unpack("C*").map {|n| sprintf("%02x", n)}.join
end
end
Of course, you'd want a BINARY column, because you're sending raw bytes to the DB. A migration such as this one:
class AddUuidToUsers
def self.up
execute "ALTER TABLE users ADD uuid BINARY(16)"
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With