From 797f80eb7d7537ccc171de61bd132205a4a55090 Mon Sep 17 00:00:00 2001 From: Andrew Bonner Date: Mon, 14 May 2018 10:54:19 -0400 Subject: [PATCH] Complete ActiveRecord. --- associations.rb | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/associations.rb b/associations.rb index 65959a1..84fb00b 100644 --- a/associations.rb +++ b/associations.rb @@ -13,25 +13,30 @@ def migrate def generate_migrations ActiveRecord::Migration.create_table :hotels do |t| - #insert our columns here + t.string :name + t.integer :room_count t.timestamps null: false end ActiveRecord::Migration.create_table :rooms do |t| - #insert our columns here + t.integer :rate + t.string :location + t.integer :hotel_id t.timestamps null: false end ActiveRecord::Migration.create_table :bookings do |t| - #insert our columns here + t.integer :guest_id + t.integer :room_id + t.datetime :check_in t.timestamps null: false end ActiveRecord::Migration.create_table :users do |t| - #insert our columns here + t.string :name t.timestamps null: false end @@ -46,26 +51,28 @@ def generate_migrations class Hotel < ActiveRecord::Base - #insert our associations here - + has_many :rooms + has_many :bookings, through: :rooms + has_many :booked_guests, through: :bookings, source: :guest + def to_s "#{name} with #{rooms.count} rooms" end end class Booking < ActiveRecord::Base - #insert our associations here - + belongs_to :guest, class_name: "User" + belongs_to :room end class Room < ActiveRecord::Base - #insert our associations here - + has_many :bookings + has_many :guests, through: :bookings, source: :users end class User < ActiveRecord::Base - #insert our associations here - + has_many :bookings, foreign_key: "guest_id" + has_many :booked_rooms, through: :bookings, source: :room end #DO NOT CHANGE ANYTHING BELOW THIS LINE. @@ -74,11 +81,11 @@ def random_loc; (('a'..'e').to_a.sample) + rand(1..5).to_s; end hotel = Hotel.create!(name: "Westin", room_count: 5) -5.times do +5.times do hotel.rooms << Room.create!( rate: [125,200,175].sample, location: random_loc - ) + ) end user = User.create!(name: "John Smith")