PostgreSQL is almost popular as SQLite as a database backend for Rails applications. Some of them uses uuid-ossp extension to change type of column id to uuid. It’s common knowledge that uuid breaks references column type when you want to reflect table relations in migration files. Actually it’s not.

Missing knowledge

When you search for articles that are about integrating uuid type into id column. Almost every one of them either say that this will break references column type in migrations or says nothing about it.

There’s workaround to use t.uuid :something_else_id thing. And it’s working great. I don’t mind. I even used it in my code. But the brilliant idea came to mi that i might fix it in Rails code. And i started digging.

Actually it works

I started to go through Rails code to search The Place. It’s hard to navigate though it. Especially when you go into large codebase for first time. So i stumbled upon migration tests and found this little gem. It works! But even Rails documentation says nothing about this. But hopefully it’s going to be fixed :)

Therefore you can fix t.references :something to work with uuid

# db/migrate/20150418012400_create_blog.rb
def change
  create_table :posts, id: :uuid
end

create_table :comments, id: :uuid do |t|
  # t.belongs_to :post, type: :uuid
  t.references :post, type: :uuid
end

# app/models/post.rb
class Post < ActiveRecord::Base
  has_many :comments
end

# app/models/comment.rb
class Comment < ActiveRecord::Base
  belongs_to :post
end

It would be lovely that migration mechanism would detect referenced column type automatically. I think i can be done. Just need to find proper place to start hacking things.

Share this on → Twitter Facebook Google+ LinkedIn Reddit