I have two models: Hurricane
and Problem
and each Hurricane
has many Problem
Now in my database I want to let users update data about each Hurricane, so I have one copy of the data that is set by the admin and each user has access to this data. When each user wants to update data about the Hurricane, I create a new copy of the admin created record and scope it so that each user sees only the newly created record that they modified. And each new record stores and 'original_id' attribute that stores the id of the model it was cloned from. However, each Problem model will still point to the original Hurricane record (created by the admin). I should also mention that each problem is belongs_to
a User
For a given user, when listing all the problems, I'd like to eagerly load all the associated Hurricanes, and instead of displaying the Hurricanes that they point to, I'd like to eagerly load the ones that they modified
I tried this:
In my app/models/problem.rb
class Problem < ActiveRecord::Base
belongs_to :hurricane
belongs_to :user_hurricane, -> (problem) { where "original_id = ? AND user_id = ?", problem.hurricane_id, problem.user_id }, class_name: 'Hurricane'
...
Then I call some think like the following
problems = Problem.includes(:user_hurricanes).where(user_id: current_user.id)
problems.each do |problem|
puts problem.user_hurricane
end
# >> always returns nil
But the user_hurricane is always nil, so it doesn't successfully eagerly load the user specific Hurricane records. How would I do that?