问题
I'm trying to store a SHA-2 256 bit checksum in a column:
create_table :checksums do |t|
t.binary :value, :null => false, :limit => 32
end
I'm storing in the value like so:
c = Checksum.new
big_num = Digest::SHA2.new.update("some string to be checksum'd").hexdigest.to_i(16)
c.value = big_num
On the assignment of big_num to c.value I get:
NoMethodError: undefined method `gsub' for #<Bignum:0x00000001ea48f8>
Anybody know what I'm doing wrong?
回答1:
If you're going to be storing your SHA2 in a binary column then you probably just want to use the digest method to get the raw SHA2 bytes:
big_num = Digest::SHA2.new.update("some string to be checksum'd").digest
Your SHA2 is a 256 bit value (32 bytes) and that won't fit in a Fixnum (which uses less than 32 or 64 bits due to internal bookkeeping bits), that's why you end up with a Bignum when you call .hexdigest.to_i(16)
. Binary columns are really just sequences of bytes (i.e. binary strings) and part of the encoding mechanism is probably using gsub to get the bytes into the format that the database expects. You're assigning a Bignum to something that expects to see a String and that doesn't work that well.
You could also use a simple string column (with :limit=> 64
) to store the .hexdigest
value instead of a 32 byte binary column.
来源:https://stackoverflow.com/questions/8555781/rails-storing-a-256-bit-checksum-as-binary-in-database