using UUID as primary key in rails and polymorph r

2020-02-03 05:09发布

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条回答
够拽才男人
2楼-- · 2020-02-03 05:32

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.

查看更多
登录 后发表回答