从 'has_many through' 关联中获取额外的属性值

Get extra attribute value from 'has_many through' association

我有以下结构:

在我的 answer 模型中:

class Answer < ApplicationRecord
  has_many :answer_test_case_results
  has_many :test_cases_result, through: :answer_test_case_results, source: :test_case
end

我的answer_test_case_result:

class AnswerTestCaseResult < ApplicationRecord
  belongs_to :answer
  belongs_to :test_case

  def get_output
    output
  end
end

我的 answer_test_case_result 模型有一个额外的属性,名为 output。在我的 answer 模型中,我想从我的 test_cases_result 关系中访问这个 output,但是这个属性 returns 只有 test_case 对象保存和关联有了这个答案。

有没有直接从我的 AnswerTestCaseResult(即 AnswerTestCaseResult.where(answer: answer, test_case: test_case))访问 output 的方法?

这种操作的例子之少令人难以置信。但现在我明白我做错了什么:我应该访问我的 has_many :answer_test_case_results,而不是 has_many :test_cases_result, through: :answer_test_case_results, source: :test_case

如果我想保留属性,对于我的情况,在语义上更合适,我可以使用:has_many :test_cases_result, class_name: "AnswerTestCaseResult"

所以我可以通过 answer.test_cases_reult.first.output 访问 output,例如。