Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created April 12, 2022 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/d080c6485a1f76eef8a6cf28090074c3 to your computer and use it in GitHub Desktop.
Save JoshCheek/d080c6485a1f76eef8a6cf28090074c3 to your computer and use it in GitHub Desktop.
Example of using UUIDs for primary keys in ActiveRecord
require 'active_record'
ActiveRecord::Base.establish_connection adapter: 'postgresql', database: 'josh_test'
ActiveRecord::Schema.define do
self.verbose = false
enable_extension 'pgcrypto'
create_table :conversations, id: :uuid do |t|
t.string :topic
end
create_table :messages, id: :uuid do |t|
t.uuid :conversation_id, null: false, index: true
t.string :body
end
end
class Conversation < ActiveRecord::Base
has_many :messages
end
class Message < ActiveRecord::Base
belongs_to :conversation
end
Conversation.create! messages: [Message.new(body: 'hello'), Message.new(body: 'world')]
pp Message.first.conversation.messages.order(body: :asc).to_a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment