问题
I'm creating a rails 3 application that will be decentralized and I need to use UUID as primary key for my tables, what would be the best gem, plugin for the Job. I also would like to know if it is possible to make in ActiveRecord polymorphic relationships without using the polymorphicable_type column for it, given the case that I'm using UUID.
I have created a demo http://github.com/boriscy/uuidrails3 that uses UUID as keys, you should check the module UUIDHelper inside lib/ and also all the migrations. There is no need to add a primary key in the database, just an index, because primary keys verify uniqueness of the field, but we don't need that with UUID.
回答1:
Put this file in the lib directory, and add this as an initializer:
class ActiveRecord::Base
set_primary_key :uuid
before_create :set_uuid
def set_uuid
self.uuid = UUID.generate(:compact)
end
end
As for the relationships, vlad is right that ActiveRecord needs to know which table a record is in to find it. If you want this kind of functionality, try something else like MongoMapper.
来源:https://stackoverflow.com/questions/2654533/using-uuid-as-primary-key-in-rails-and-polymorph-relationships