使用Rails 3.1和sqlite3进行开发、测试环境。
在迁移中添加了一个新表:
create_table :api_keys do |t|
t.string :api_key
t.integer :user_id
t.timestamps
end
这会生成一个具有以下架构的表:
create_table "api_keys", :force => true do |t|
t.string "api_key"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end
在 ActiveRecord 模型中:
before_create :fill_api_key
private
def fill_api_key
self.api_key = SecureRandom.hex(30)
end
ActiveRecord的动态查找器方法find_by_api_key(api_key)
不起作用(返回零)。与以下相同:
ApiKey.where({:api_key => 'something'}).first
在 sqlite3 中,我执行以下操作:
insert into api_keys (id, api_key) values (-1, '12345');
如果我现在运行选择:
select api_keys.* from api_keys where api_keys.api_key = '12345';
就会找到该记录。
如果我运行未过滤的选择,则会显示从我的应用程序创建的预先存在的数据:
select api_keys.* from api_keys;
如果我尝试通过将这些预先存在的记录之一中的长十六进制字符串粘贴到查询中来查找预先存在的记录:
select api_keys.* from api_keys where api_keys.api_key = 'long hex string';
然后它不返回任何结果。如果我尝试这样做:
select api_keys.* from api_keys where api_keys.api_key like 'long hex string';
然后我得到了一场比赛。
我已经在 api_keys.api_key 上创建了索引,但这没有效果。
此问题会影响我的应用程序中的另一个模型,该模型使用 Digest::SHA1::hexdigest 生成类似的随机十六进制数字字符串。
James