Created
April 12, 2022 18:03
-
-
Save JoshCheek/d080c6485a1f76eef8a6cf28090074c3 to your computer and use it in GitHub Desktop.
Example of using UUIDs for primary keys in ActiveRecord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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