【问题标题】:Rails - Do I need a join table for this or column on each model?Rails - 我是否需要每个模型上的这个或列的连接表?
【发布时间】:2014-05-16 04:46:32
【问题描述】:

我正在构建一个应用程序,其中会有预订的旅行。每次旅行将在不同的日期提供,每次预订都属于一天。我的问题是,我应该在每个模型上创建一个“日”列(旅游和预订)还是应该创建某种关联和/或连接表,如下所示?

我只是不确定哪个更合适。我的目标是为每次旅行添加一组日期,然后在预订页面上显示这些日期并允许用户选择日期。

型号
预订
旅游

days_tours(加入表)

协会
旅游有很多:days_tours
游览 has_many :days, through: :days_tours
一天有很多:days_tours
day has_many :tours, through: :days_tours
预订 has_one :day

【问题讨论】:

  • 使用这个:apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many
  • @UriAgassi 不不不不。不要使用has_and_belongs_to_many,使用 has_many :through 以获得更大的灵活性(来自 Rails 样式指南:github.com/bbatsov/rails-style-guide#activerecord
  • 我继续创建了一个 has_many :through 关联。谢谢。

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

我将使用具有三个外键的 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 灵活,尤其是当您加入两个以上模型时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2013-12-04
    相关资源
    最近更新 更多