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
t.integer :user_id
t.timestamps
end
This produces a table with the following schema:
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
In ActiveRecord model:
before_create :fill_api_key
private
def fill_api_key
self.api_key = SecureRandom.hex(30)
end
ActiveRecord's dynamic finder method find_by_api_key(api_key)
does not work (returns nil). Same with:
ApiKey.where({:api_key => 'something'}).first
In sqlite3, I do the following:
insert into api_keys (id, api_key) values (-1, '12345');
If I now run a select:
select api_keys.* from api_keys where api_keys.api_key = '12345';
the record will be found.
Pre-existing data created from my app is displayed if I run an unfiltered select:
select api_keys.* from api_keys;
If I try to find a pre-existing record by pasting into my query a long hex string from one of those pre-existing records:
select api_keys.* from api_keys where api_keys.api_key = 'long hex string';
then it returns no results. If I try this instead:
select api_keys.* from api_keys where api_keys.api_key like 'long hex string';
Then I get a match.
I have created an index on api_keys.api_key but that had no effect.
This problem affects one other model in my application that produces a similar string of random hex digits using Digest::SHA1::hexdigest instead.
James