Skip to content

Commit

Permalink
Merge pull request #164 from ifad/bugfix/fix-issue-with-through-assoc…
Browse files Browse the repository at this point in the history
…iations-163

Fix issue with through associations
  • Loading branch information
tagliala authored May 20, 2022
2 parents ffbdc51 + 74a2586 commit e2c790e
Show file tree
Hide file tree
Showing 3 changed files with 24 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
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

0 comments on commit e2c790e

Please sign in to comment.