سؤال

I'm building an app where there will be tours with reservations. Each tour will be available on different days and each reservation will belong to a single day. My question is, should I create a "day" column on each model I want to use it on (tour and reservation) or should I create some kind of association and/or join table, like below?

I'm just not sure which one would be more appropriate. My goal is to add a set of days for each tour, then display those days on the reservations page and allow users to choose a day.

Models
reservations
tours
days
days_tours (join table)

Associations
tour has_many :days_tours
tour has_many :days, through: :days_tours
day has_many :days_tours
day has_many :tours, through: :days_tours
reservation has_one :day

هل كانت مفيدة؟

المحلول

I would use a Reservations table with three foreign keys: user_id, tour_id, and day_id.

Then that table could serve as a join table.

Then you could set up the following, depending on your needs:

# User
  has_many :reservations
  has_many :tours, through: :reservations
  has_many :days, through: :reservations

# Tour
  has_many :reservations
  has_many :days, through: :reservations
  has_many :users, through: :reservations

# Day
  has_many :reservations
  has_many :users, through: :reservations
  has_many :tours, through: :reservations

Also, remember every has_many or has_one on one side needs a belongs_to on the other side.

# Reservation
  belongs_to :user
  belongs_to :tour
  belongs_to :day

As for has_and_belongs_to_many -- it's often simpler to set up, but it's far less flexible than has_many :through, especially if you're joining more than two models.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top