Reputation: 1168
I have the following structure:
In my answer
model:
class Answer < ApplicationRecord
has_many :answer_test_case_results
has_many :test_cases_result, through: :answer_test_case_results, source: :test_case
end
My answer_test_case_result
:
class AnswerTestCaseResult < ApplicationRecord
belongs_to :answer
belongs_to :test_case
def get_output
output
end
end
My answer_test_case_result
model has an extra attribute, named output
. In my answer
model I would like access this output
from my test_cases_result
relationship, however the way it is this attribute returns only the test_case
objects saved and associated with this answer.
There is a way to access the output
without a query directly from my AnswerTestCaseResult (that is, AnswerTestCaseResult.where(answer: answer, test_case: test_case)
)?
Upvotes: 1
Views: 198
Reputation: 1168
The scarcity of examples of this kind of operation is unbelievable. But now I understand what I was doing wrong: I should access my has_many :answer_test_case_results
, not has_many :test_cases_result, through: :answer_test_case_results, source: :test_case
.
And if I want to leave the attribute, for my case, more appropriate semantically, I can use: has_many :test_cases_result, class_name: "AnswerTestCaseResult"
So I can access output
through answer.test_cases_reult.first.output
, for instance.
Upvotes: 1