如何为 Decision、Choice 和 ChoiceSet 关系建模?

How to model a Decision, Choice, and ChoiceSet relationship?

几天来我一直在为这个数据建模问题绞尽脑汁,决定向你们这些优秀的人寻求帮助。虽然我已经与 Rails 一起工作了 7 年多,但这种关系建模正在逃避我。

我有一个Decision模型,它基本上由一个:question属性组成,例如:

Which team will win the Super Bowl this year?

对于每一个@decision,都有一组对应的@choices,例如:

  1. 达拉斯牛仔
  2. 新英格兰爱国者
  3. 纽约巨人队
  4. 绿湾包装工队

我想用模型对这组@choices进行分组。我们称其为 ChoiceSet.

因此,用简单的英语总结所需的关系:

A Decision has many Choices through a ChoiceSet.

到目前为止,还不错。这就是我感到困惑的地方。通常人们会这样建模:

model Decision < ActiveRecord::Base
  has_many :choice_sets
  has_many :choices, through: :choice_sets
end

model Choice < ActiveRecord::Base
  has_many :choice_sets
  has_many :decisions, through: :choice_sets
end

model ChoiceSet < ActiveRecord::Base
  belongs_to :decision
  belongs_to :choice
end

这里有一个警告:这是建模的方式,一个决定可能有多个选择集。我如何对此进行建模,以便一个决策只能有一个选择集?

有这么简单吗(把has_many :choice_sets改成has_one :choice_set就可以了?

model Decision < ActiveRecord::Base
  has_one :choice_set
  has_many :choices, through: :choice_set
end

model Choice < ActiveRecord::Base
  has_many :choice_sets
  has_many :decisions, through: :choice_sets
end

model ChoiceSet < ActiveRecord::Base
  belongs_to :decision
  belongs_to :choice
end

感谢您的帮助。

编辑

正如这个问题的答案所表明的那样,我应该指定我想避免说 Choice :belongs_to Decision 这样我就不需要创建新的 Choice 记录除了 decision_id 之外,一切都一样。例如,我不希望 "Dallas Cowboys".

有 2 Choice 条记录

好吧,如果我们说多个决策可以有相同的选择集:

Which team will win the Super Bowl this year?

Which team will come in second in the Super Bowl this year?

我们知道 ChoiceSet 和 Decision 之间存在一对多的关系

每个 ChoiceSet 可以有很多 Choices,但是您还说每个 Choice 可以属于很多 ChoiceSets...这意味着您需要另一个连接 table。这种关系类似于...

model Decision < ActiveRecord::Base
  belongs_to :choice_set
  has_many :choices, through: :choice_set
end

model ChoiceSet < ActiveRecord::Base
  has_many :decisions
  has_many :choice_set_choice_links
  has_many :choices, through: :choice_set_choice_links
end

model ChoiceSetChoiceLink < ActiveRecord::Base
  belongs_to :choice_set
  belongs_to :choice

model Choice < ActiveRecord::Base
  has_many choice_set_choice_links
  has_many choice_sets, through: choice_set_choice_links
  has_many :decisions, through: :choice_sets
end

模型决策有 choice_set_id 模型 ChoiceSetChoiceLink 有 choice_set_idchoice_id