Alexander Spanos
Alexander Spanos

Reputation: 177

Rails model concept

I am building an accommodation booking website on rails and I am confused about one aspect of the models. So normally the way I know of building it is by having a Room model that has many Reservations and the Reservation model belongs to the Room model. Problem is that this time I want the visitor to be able to book multiple rooms on one reservation. Is the Room has many Reservations association correct for that usage? Can anyone help me find a way of building that, do I have to use a single form that makes multiple records? I am sorry for my ignorance, it's the first time a concept like this fall into my hands.

Thank you all very much

Upvotes: 0

Views: 24

Answers (1)

andrew21
andrew21

Reputation: 640

You essentially need to have a many-to-many relationship defined and rails has a couple options to do so.

One option is the has_and_belongs_to_many relationship, which you can read up on here. However, my preferred option is the has_many, through: [model] approach as such:

class Room
  has_many :room_reservations
  has_many :reservations, through: :room_reservations
end

class Reservation
  has_many :room_reservations
  has_many :rooms, through: :room_reservations
end

class RoomReservation
  belongs_to :room
  belongs_to :reservation
end

essentially you have an intermediate table to create the many-to-many join.

Upvotes: 3

Related Questions