Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue with through associations #164

Merged
merged 1 commit into from
May 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/chrono_model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ def chrono?
prepend ChronoModel::Patches::Preloader::Association
end

ActiveRecord::Associations::Preloader::ThroughAssociation.instance_eval do
prepend ChronoModel::Patches::Preloader::ThroughAssociation
end

if defined?(Rails::DBConsole)
Rails::DBConsole.instance_eval do
if Rails.version < '6.1'
Expand Down
17 changes: 17 additions & 0 deletions lib/chrono_model/patches/preloader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,23 @@ def build_scope
return scope
end
end

module ThroughAssociation
# Builds the preloader scope taking into account a potential
# +as_of_time+ passed down the call chain starting at the
# end user invocation.
#
def through_scope
scope = super
return unless scope # Rails 5.2 may not return a scope

if preload_scope.try(:as_of_time)
scope = scope.as_of(preload_scope.as_of_time)
end

scope
end
end
end

end
Expand Down
3 changes: 3 additions & 0 deletions spec/chrono_model/time_machine/as_of_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,9 @@
it { expect(Foo.as_of($t.foo.ts[0]).includes(:bars, :sub_bars).first.sub_bars.first).to be nil }
it { expect(Foo.as_of($t.foo.ts[1]).includes(:bars, :sub_bars).first.sub_bars.first).to be nil }

it { expect(Foo.as_of($t.bar.ts[0]).includes(:sub_bars).first.bars.first.sub_bars.first).to be nil }
it { expect(Foo.as_of($t.subbar.ts[0]).includes(:sub_bars).first.bars.first.sub_bars.first.name).to eq 'sub-bar' }

it { expect(Foo.as_of($t.subbar.ts[0]).includes(:bars, :sub_bars).first.sub_bars.first.name).to eq 'sub-bar' }
it { expect(Foo.as_of($t.subbar.ts[1]).includes(:bars, :sub_bars).first.sub_bars.first.name).to eq 'bar sub-bar' }
it { expect(Foo.as_of($t.subbar.ts[2]).includes(:bars, :sub_bars).first.sub_bars.first.name).to eq 'sub-bar sub-bar' }
Expand Down