Skip to content

Commit

Permalink
Fix issue with through associations
Browse files Browse the repository at this point in the history
Fix #163
  • Loading branch information
tagliala committed May 20, 2022
1 parent ffbdc51 commit 59b14a4
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
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
16 changes: 16 additions & 0 deletions lib/chrono_model/patches/preloader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,22 @@ 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

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

scope
end
end
end

end
Expand Down
2 changes: 2 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,8 @@
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(: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

0 comments on commit 59b14a4

Please sign in to comment.