Skip to content
This repository was archived by the owner on Jul 11, 2020. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion lib/daylight/associations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions spec/lib/daylight/associations_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down