I’m trying to set up a model using UUIDs instead of auto-increment. Without bothering with the UUID part, here is what my code looks like:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users, :id => false do |t|
t.column :id, 'char(36) binary', :null => false, :primary => true
t.string :email
t.string :username
t.string :password_hash
t.string :password_salt
t.timestamps
end
end
end
The user model just has:
class User < ActiveRecord::Base
end
When I try to assign the id in the console it doesn’t take:
ruby-1.9.3-p0 > u = User.new
=> #<User id: nil, email: nil, username: nil, password_hash: nil, password_salt: nil, created_at: nil, updated_at: nil>
ruby-1.9.3-p0 > u.id = 'stuff'
=> "stuff"
ruby-1.9.3-p0 > u.id
=> nil
ruby-1.9.3-p0 > u.id = UUIDTools::UUID.random_create.to_s
=> "d3cd5bef-22b4-4fb1-b00f-10d8bbc94dc1"
ruby-1.9.3-p0 > u.id
=> nil
ruby-1.9.3-p0 > u.email = 'stuff'
=> "stuff"
ruby-1.9.3-p0 > u.email
=> "stuff"
Why can I not assign the id manually? If I name the column something else it works, but I’d prefer to be able to use the id field so I don’t have to override all the rails magic. It seems to work fine in Rails 2. Is there some Rails setting that protects the id from changes?
Try using this:
in your models.
There’s also a activeuuid plugin.
This SO post seems to back up the
set_primary_keything, at least partially.