Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

activerecord - using UUID as primary key in rails and polymorph relationships

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...