sqlite3 varchar matching with “like” but not “=”

前端 未结 2 939
走了就别回头了
走了就别回头了 2021-01-03 12:32

Using Rails 3.1 and sqlite3 for development, test environments.

Added a new table in a migration:

create_table :api_keys do |t|
  t.string :api_key
          


        
2条回答
  •  萌比男神i
    2021-01-03 13:17

    OK, I think I've figured it out. The problem isn't that this is Rails 3.1, it's that you've likely moved from Ruby 1.8.7 to Ruby 1.9.2.

    In Ruby 1.9, all strings are now encoded. By default, all strings should be UTF-8, however, SecureRandom.hex(30) returns an encoding of ASCII-8BIT.

    You can confirm this in sqlite3 by using this command: .dump api_keys and you'll probably see that the api_key field looks something like this:

    INSERT INTO "api_keys" VALUES(1,X'376433356530[...]',1);    
    INSERT INTO "api_keys" VALUES(1,'1234567890[...]',1);
    

    The first one is the api_key generated by SecureRandom. The second is the one created by typing into the console. The X indicates the field is encoded as a blob, not as a string.

    To get around this, change your fill_api_key to this:

    self.api_key = SecureRandom.hex(30).force_encoding('UTF-8')
    

    I just got bit big time by this, so hopefully it helps you out.

    There are some good details about the changes to String in 1.9 here: http://blog.grayproductions.net/articles/ruby_19s_string

提交回复
热议问题