I’m working with the UUIDTools gem in Rails 3 and running into some problems. It seems to work fine in practice:
> item = Item.create
=> #<Item uuid: "e9d00043-9200-4497-a55c-509c5de3dd88", created_at: "2012-01-09 01:56:49", updated_at: "2012-01-09 01:56:49">
> item.id
=> "e9d00043-9200-4497-a55c-509c5de3dd88"
But then in my specs it tells a different story:
require 'spec_helper'
describe Item do
it 'should assign an id' do
item = Item.create
puts "item id: #{item.id}"
end
end
Running this spec shows:
item id: 5
.
Finished in 2.21 seconds
1 example, 0 failures
Where’s my guid? There doesn’t seem to be any pattern to what id is assigned, I’ve run this a bunch of times and seen it go anywhere from 0 to up in the thousands.
Here is my migration:
class CreateItems < ActiveRecord::Migration
def change
create_table :items, :id => false do |t|
t.string :uuid, :null => false, :primary => true
t.timestamps
end
add_index :items, :uuid, :unique => true
end
end
My model:
require 'uuid_helper'
class Item < ActiveRecord::Base
include UUIDHelper
end
And my uuid_helper:
module UUIDHelper
def self.included(base)
base.class_eval do
set_primary_key :uuid
attr_readonly :uuid
before_create :set_uuid
private
def set_uuid
self.uuid = UUIDTools::UUID.random_create.to_s
end
end
end
end
Putting some debugger logic into set_uuid I’ve discovered that it’s doing to_i on the uuid at some point. Any suggestions?
Update This seems to be a bug in the Rails test environment. When I run RAILS_ENV=test rails console I get the same behavior as in the specs–the guids are chopped off.
Alright, the answer was to upgrade to Rails 3.1.3 from 3.1.1.