From e1bd009dff9b6c1bfd91751e87b3989c1c7a1866 Mon Sep 17 00:00:00 2001 From: Dan Kubb Date: Wed, 3 Jun 2009 22:47:08 -0700 Subject: [PATCH] Fixed bug where many to one query would be unscoped [#881 state:resolved] --- lib/dm-core/query.rb | 11 +++++------ spec/public/model/relationship_spec.rb | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/lib/dm-core/query.rb b/lib/dm-core/query.rb index b4599db0..95d9acf6 100644 --- a/lib/dm-core/query.rb +++ b/lib/dm-core/query.rb @@ -977,16 +977,15 @@ def append_condition(subject, bind_value, operator = :eql) subject when Associations::Relationship - # TODO: handle compound keys. Consider pushing this into the adapter - source_key = subject.source_key.first - target_key = subject.target_key.first - # TODO: when the bind_value is a Collection, and it is not loaded # then use a subquery to scope the results rather than lazy loading # it just to retrieve the Resource key - if (resources = Array(bind_value).select { |r| r.saved? }).any? - source_values = resources.map { |r| target_key.get(r) } + # TODO: handle compound keys. Consider pushing this into the adapter + source_key = subject.source_key.first + target_key = subject.target_key.first + + if (source_values = Array(bind_value).map { |resource| target_key.get!(resource) }.compact).any? append_condition(source_key, source_values, operator) end diff --git a/spec/public/model/relationship_spec.rb b/spec/public/model/relationship_spec.rb index ebf5bae4..d07a45b8 100644 --- a/spec/public/model/relationship_spec.rb +++ b/spec/public/model/relationship_spec.rb @@ -507,6 +507,27 @@ def n end supported_by :all do + describe 'querying for a parent resource when only the foreign key is set' do + before :all do + # create a car that would be returned if the query is not + # scoped properly to retrieve @car + Car.create + + @car = Car.create + engine = Engine.new(:car_id => @car.id) + + @return = engine.car + end + + it 'should return a Resource' do + @return.should be_kind_of(DataMapper::Resource) + end + + it 'should return expected Resource' do + @return.should eql(@car) + end + end + describe 'querying for a parent resource' do before :all do @car = Car.create