3

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
4

1 回答 1

4

you can use the after_initialize callback, that is called every time an object of your class is instantiated.

 class User < ActiveRecord::Base
   after_initialize :generate_guid, unless: :guid
   def generate_guid
     self.guid = # your method here
   end
 end

you can also set this field to be a primary key in your migration:

create_table :users, primary_key: :guid do |t| 

however, do you really need to create a guid every time you instantiate an object ? It seems really computationaly expensive. And as someone commented, be warned that rails sometimes behaves weirdly when you get out of common patterns and conventions...

于 2012-12-02T19:28:22.990 回答