I have the following three models:
A TestRun model, A TestResult model and a Test model. A TestRun has many TestResults, and a TestResult has one Test. (A test can have many results but its not really relevant for this question)
I am eager loading everything into a test run using the following:
test_run = TestRun.includes(test_results: [:test]).find(params[:id])
This works fine, creating three separate queries. The problem now is that I want to scope one of the queries. I want to exclude a field (called 'log') from the test_results in this query. I created a scope in the TestResult model but I am not sure how to apply it in this situation.
I could do something like this:
tr = TestRun.find(id)
tr.test_results.without_log.include(:test).load
Which works except for whenever I call the third association it isn't preloaded. E.g.
tr.test_results[1].test #This causes an additonal query
I am trying to keep one TestRun model with all the other associations preloaded. Is this possible?
Edit:
def self.without_log
select(column_names-['log'])
end
without_log
looks like butTestRun.find(id).test_results.includes(:test).without_log
should work if without log is just a where clause. Check This Out for More. You can force eager loading usingeager_load
– engineersmnky