我正在构建一个应用程序,其中将有预订游览。每个旅游将在不同的日子提供,每个预订将属于一天。我的问题是,我应该创建一个" day"我希望在每个模型上使用它(游览和预订),或者我应该创建某种关联和/或联接表,如下所示?
我不确定哪一个更合适。我的目标是为每个游览添加一组日期,然后在预订页面上显示这些日子,并允许用户选择一天。
模型
保留
旅游
天
days_tours(加入表)
协会
tour has_many:days_tours
tour has_many:days,through :: days_tours
day has_many:days_tours
day has_many:游览,通过:: days_tours
预订has_one:day
答案 0 :(得分:2)
我会使用带有三个外键的Reservations表:user_id,tour_id和day_id。
然后该表可以作为连接表。
然后,您可以根据需要设置以下内容:
# 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
另外,请记住一方的每个has_many或has_one都需要另一方的belongs_to。
# Reservation
belongs_to :user
belongs_to :tour
belongs_to :day
至于has_and_belongs_to_many - 它的设置通常比较简单,但它的灵活性远远低于has_many:through,特别是如果你加入两个以上的模型。