I'm new to Ruby & Rails... the goal is to create a User class whose primary key (id) is not an integer, but a GUID. I think I have the ActiveRecord end of things setup properly (not auto-generating an id column with type integer, but with column id of type string instead), and a function that can generate a GUID.
The only missing piece at this point is getting Rails to initialize a new User class' with an id using the *generate_guid* function I had wrote.
My question: How do I get Rails to initialize id with a random GUID? For example...
@user = User.new
@user.id
> 'AG5CE52' # <-- A randomly generated GUID...
It's also important to consider that if an instance of User is loaded from the database, it shouldn't change the id of the already existing user; a GUID should only be generated when I user is being created for the first time.
Here are some code samples:
The model:
class User < ActiveRecord::Base
before_create :generate_guid # This doesn't seem to do anything (when I call User.new)
set_primary_key :id
protected
def generate_guid
begin
id = SecureRandom.urlsafe_base64
end while User.where(:id => id).exists?
self.id = id
end
end
The migration:
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users, {:id => false} do |t|
t.string :id
...
end
execute "ALTER TABLE users ADD PRIMARY KEY (id);"
end
Suggestions are appreciated!
- Dave