From 22ac85d8ea5a76e0167a215bf1974ba2fc044e30 Mon Sep 17 00:00:00 2001 From: nik kov Date: Sun, 3 May 2015 23:18:05 -0400 Subject: [PATCH] belongs_to resolution when missing foreign key --- lib/daylight/associations.rb | 6 +++++- spec/lib/daylight/associations_spec.rb | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/daylight/associations.rb b/lib/daylight/associations.rb index aed7991..2d27694 100644 --- a/lib/daylight/associations.rb +++ b/lib/daylight/associations.rb @@ -98,7 +98,11 @@ def belongs_to name, options={} # setup the resource_proxy to fetch the results define_cached_method reflection.name, cache_key: nested_attribute_key do - reflection.klass.find(send(reflection.foreign_key)) + if attributes.include? name + attributes[name] + else + reflection.klass.find(send(reflection.foreign_key)) + end end # Defines a setter caching the value in an instance variable for later diff --git a/spec/lib/daylight/associations_spec.rb b/spec/lib/daylight/associations_spec.rb index 07fab14..e588273 100644 --- a/spec/lib/daylight/associations_spec.rb +++ b/spec/lib/daylight/associations_spec.rb @@ -20,6 +20,10 @@ def id; 123; end def parent_id; 456; end end + class AnotherAssociationTestClass < Daylight::API + belongs_to :parent, class_name: 'RelatedTestClass' + end + describe :has_many do before do @@ -116,6 +120,7 @@ def parent_id; 456; end [RelatedTestClass, AssociationsTestClass].each do |clazz| stub_request(:get, %r{#{clazz.site}}).to_return(body: data.to_json) end + stub_request(:get, %r{#{AnotherAssociationTestClass.site}}).to_return(body: { parent: data }.to_json) end it 'still fetches the parent object' do @@ -138,6 +143,13 @@ def parent_id; 456; end resource.attributes['parent_id'].should == 789 end + + it 'fetches the parent object if no foreign key attr is present' do + resource = AnotherAssociationTestClass.find(1) + + resource.parent.should_not be_nil + resource.parent.name.should == 'three' + end end describe :belongs_to_through do