-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhotels.rb
53 lines (42 loc) · 1.8 KB
/
hotels.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
## General tips:
# Do obvious associations first.
# Do more direct connections/associations first
# Read RSpec tests written for you to identify what the methods are called before you write them
# Read ActiveRecord errors - AR is often smart enough that just the error message itself will tell you how to fix it
#########################
# in app/models/user.rb #
#########################
class User < ActiveRecord::Base
# If we don't put foreign_key: 'guest_id', then AR looks for user_id in the bookings table, which doesn't exist! yo
has_many :bookings, foreign_key: 'guest_id'
has_many :booked_rooms, through: :bookings, source: :room
# source: :room singular, because (1) AR error said so, (2) look at Booking model - says belongs_to :room singular, and we're using this association to obtain the rooms
has_many :booked_hotels, through: :booked_rooms, source: :hotel
end
############################
# in app/models/booking.rb #
############################
class Booking < ActiveRecord::Base
# If we don't put class_name: 'User', then AR looks for a model called Guest which doesn't exist
belongs_to :guest, class_name: 'User'
belongs_to :room
has_one :hotel, through: :room
# Incorrect association to try to get booking.hotel to work:
# belongs_to :hotel, through: :room
# Reason: The belongs_to association CANNOT have the "through" option. However, "through" does work with the has_many association.
end
#########################
# in app/models/room.rb #
#########################
class Room < ActiveRecord::Base
belongs_to :hotel
has_many :bookings
end
##########################
# in app/models/hotel.rb #
##########################
class Hotel < ActiveRecord::Base
has_many :rooms
has_many :bookings, through: :rooms
has_many :booked_guests, through: :bookings, source: :guest
end