Skip to content

Instantly share code, notes, and snippets.

@lesterzone
Forked from mateuszbialowas/scratch.rb
Created August 12, 2022 15:52
Show Gist options
  • Save lesterzone/1d2b87b7c6888c221f0783dc3736b829 to your computer and use it in GitHub Desktop.
Save lesterzone/1d2b87b7c6888c221f0783dc3736b829 to your computer and use it in GitHub Desktop.
ar-mapping-custom-pk-fk
# frozen_string_literal: true
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'pry'
gem "sqlite3"
gem 'activerecord'
end
require 'active_record'
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :bookings, primary_key: :booking_id, force: true do |t|
t.datetime :start_date, null: false
t.datetime :end_date, null: false
t.belongs_to :room, null: false
t.belongs_to :guest, null: false
end
create_table :rooms, primary_key: :room_id, force: true do |t|
t.integer :room_number, null: false, default: 1, unique: true
t.string :room_type, null: false, default: 'standard_room'
end
create_table :guests, primary_key: :guest_id, force: true do |t|
t.string :guest_name, null: false
t.string :guest_passport_no, null: false, unique: true
t.string :guest_phone, null: false , unique: true
end
add_foreign_key :bookings, :rooms, column: :room_id, primary_key: :room_id
add_foreign_key :bookings, :guests, column: :guest_id, primary_key: :guest_id
end
class Booking < ActiveRecord::Base
self.primary_key = :booking_id
belongs_to :room
belongs_to :guest
end
class Guest < ActiveRecord::Base
self.primary_key = :guest_id
has_many :bookings
end
class Room < ActiveRecord::Base
self.primary_key = :room_id
has_many :bookings
end
Booking.create!(
start_date: Date.new,
end_date: Date.new,
room: Room.create,
guest: Guest.create(guest_name: :sth, guest_passport_no: :sth, guest_phone: :sth)
)
require 'pry'
binding.pry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment