Rails:使用二进制值查询二进制列不返回任何内容

时间:2011-12-20 18:35:35

标签: ruby-on-rails binary

我有一个包含256位校验和的二进制列。我可以存储校验和,但是当我尝试通过校验和进行查询时,不会返回任何内容。

d = Digest::SHA2.new
d.update "large str i'm creating the hash with"
begin
    codebase = Codebase.find_or_create_by_checksum(d.digest)
rescue ActiveRecord::StatementInvalid => e
    # handle duplicate record error
end

我已经尝试过哪里和不同版本的find。什么都没有回来。当我使用find_or_create_by_checksum时,由于它没有找到任何东西,它会尝试创建它并引发异常,因为我在校验和列上有一个uniq索引,但我仍然需要能够获得具有匹配校验和的记录。 / p>

    create_table :codebases do |t|
        t.binary :checksum, :null => false, :limit => 32
    end

    add_index :codebases, :checksum, :unique => true, :name => 'name_of_the_codebas_uniq_index'

有人知道怎么做吗?

1 个答案:

答案 0 :(得分:0)

因此,如果它在数据库上的二进制文件,我无法重现:

迁移:

class Checksum < ActiveRecord::Migration
  def up
    create_table :checksums do |t|
        t.binary :checksum, :null => false, :limit => 32
    end
  end

  def down
  end
end

然后在rails控制台上尝试:

ruby-1.9.2-p290 :009 > Checksum.create(:checksum => digest.digest)
  SQL (0.4ms)  INSERT INTO "checksums" ("checksum") VALUES (?)  [["checksum", ",&\xB4kh\xFF\xC6\x8F\xF9\x9BE<\x1D0A4\x13B-pd\x83\xBF\xA0\xF9\x8A^\x88bf\xE7\xAE"]]
 => #<Checksum id: 1, checksum: ",&\xB4kh\xFF\xC6\x8F\xF9\x9BE<\x1D0A4\x13B-pd\x83\xBF\xA0\xF9\x8A^\x88bf\xE7\xAE"> 

ruby-1.9.2-p290 :010 > Checksum.first
  Checksum Load (0.2ms)  SELECT "checksums".* FROM "checksums" LIMIT 1
 => #<Checksum id: 1, checksum: ",&\xB4kh\xFF\xC6\x8F\xF9\x9BE<\x1D0A4\x13B-pd\x83\xBF\xA0\xF9\x8A^\x88bf\xE7\xAE"> 

ruby-1.9.2-p290 :011 > Checksum.find_by_checksum(digest.digest)
  Checksum Load (0.1ms)  SELECT "checksums".* FROM "checksums" WHERE "checksums"."checksum" = x'2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae' LIMIT 1
 => #<Checksum id: 1, checksum: ",&\xB4kh\xFF\xC6\x8F\xF9\x9BE<\x1D0A4\x13B-pd\x83\xBF\xA0\xF9\x8A^\x88bf\xE7\xAE"> 

所以它按预期工作.....