【问题标题】:ActiveRecord Association for Grades App成绩应用程序的 ActiveRecord 协会
【发布时间】:2013-06-10 17:15:40
【问题描述】:

有点难以用标题来解释。

我正在使用 Ruby on Rails 制作一个测试成绩应用程序,但无法确定最佳 ActiveRecord 关联设置。

理想情况下:有很多用户,有很多测试。我需要存储每个测试的每个用户的分数。现在我有这个:

class User < ActiveRecord::Base
  has_many :tests
  has_many :scores, :through => :tests
end

class Test < ActiveRecord::Base
  has_many :scores
end

class Scores < ActiveRecord::Base
  belongs_to :users
  belongs_to :tests
end

虽然看起来不太对劲。我想知道这个约定。谢谢。

【问题讨论】:

  • 顺便说一句,我认为注意这确实是一个数据库设计问题可能很有用,Rails 的 ActiveRecord 位于表之上这一事实是一个附带的细节。我不是在批评这个问题。我只是觉得指出这一点会很有趣。

标签: ruby-on-rails database database-design activerecord associations


【解决方案1】:

我会使用三个表/模型:

  1. test
  2. user(或者,可能更好,student
  3. test_result,具有test_iduser_idscore

对应的Ruby代码:

class User < ActiveRecord::Base
  has_many :tests, through: :test_results
end

class Test < ActiveRecord::Base
  has_many :users, through: :test_results
end

class TestResult < ActiveRecord::Base
  belongs_to :test
  belongs_to :user
end

【讨论】:

  • 所以 test_result 将属于_to test 和 user?
  • 它是teststest_results,而不是相反,因为test_results 是连接testsusers 的东西。这样想:我与任何特定测试有关系的唯一原因是因为我参加了那个测试。如果我要参加美国总统考试和内战考试,jason.tests 将返回这两项考试,而不是三角学考试,因为我没有参加。希望这种思维方式能说明问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-09
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多