Skip to content

Commit

Permalink
Fix array association preoperly preload when using query constraints
Browse files Browse the repository at this point in the history
  • Loading branch information
crashtech committed Jan 5, 2024
1 parent 9ddd648 commit 6a192af
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 8 deletions.
14 changes: 7 additions & 7 deletions lib/torque/postgresql/associations/preloader/loader_query.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,20 @@ def foreign_column

def load_records_for_keys(keys, &block)
condition = query_condition_for(keys)
return super if condition.nil?

scope.where(condition).load(&block)
end

def query_condition_for(keys)
if connected_through_array?
value = scope.cast_for_condition(foreign_column, keys.to_a)
scope.table[association_key_name].overlaps(value)
else
{ association_key_name => keys }
end
return unless connected_through_array?

value = scope.cast_for_condition(foreign_column, keys.to_a)
scope.table[association_key_name].overlaps(value)
end

def connected_through_array?
foreign_column.array?
!association_key_name.is_a?(Array) && foreign_column.array?
end
end

Expand Down
2 changes: 1 addition & 1 deletion lib/torque/postgresql/version.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

module Torque
module PostgreSQL
VERSION = '3.3.0'
VERSION = '3.3.1'
end
end
39 changes: 39 additions & 0 deletions spec/tests/has_many_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,45 @@
expect(query.to_sql).to match(/INNER JOIN "texts"/)
expect { query.load }.not_to raise_error
end

context 'with query constraint' do
let(:activity) { Activity.create! }

before do
Post.query_constraints :author_id, :id
Activity.query_constraints :author_id, :id
Activity.has_many :posts
end

after do
Post.instance_variable_set(:@has_query_constraints, false)
Post.instance_variable_set(:@query_constraints_list, nil)
Post.instance_variable_set(:@_query_constraints_list, nil)
Activity.instance_variable_set(:@has_query_constraints, false)
Activity.instance_variable_set(:@query_constraints_list, nil)
Activity.instance_variable_set(:@_query_constraints_list, nil)
end

it 'properly preload records' do
FactoryBot.create_list(:post, 5, activity: activity)
entries = Activity.all.includes(:posts).load

expect(entries.size).to be_eql(1)
expect(entries.first.posts).to be_loaded
expect(entries.first.posts.size).to be_eql(5)
end

it 'properly preload records using preloader' do
FactoryBot.create_list(:post, 5, activity: activity)
entries = ActiveRecord::Associations::Preloader.new(
records: Activity.all,
associations: [:posts],
).call.first.records_by_owner

expect(entries.size).to be_eql(1)
expect(entries.values.first.size).to be_eql(5)
end
end
end

context 'on array' do
Expand Down

0 comments on commit 6a192af

Please sign in to comment.