Skip to content

Commit 2659496

Browse files
guilleiguaranrafaelfranca
authored andcommitted
Merge pull request #100 from DisruptionCorporation/has-one-for-non-singleton
has_one fallback works when target is not a Singleton
1 parent f4ac23e commit 2659496

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

lib/active_resource/associations.rb

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def has_many(name, options = {})
6767
# If the response body does not contain an attribute matching the association name
6868
# a request is sent to a singelton path under the current resource.
6969
# For example, if a Product class <tt>has_one :inventory</tt> calling <tt>Product#inventory</tt>
70-
# will generate a request on /product/:product_id/inventory.json.
70+
# will generate a request on /products/:product_id/inventory.json.
7171
#
7272
def has_one(name, options = {})
7373
Builder::HasOne.build(self, name, options)
@@ -161,8 +161,10 @@ def defines_has_one_finder_method(method_name, association_model)
161161
instance_variable_get(ivar_name)
162162
elsif attributes.include?(method_name)
163163
attributes[method_name]
164-
else
164+
elsif association_model.respond_to?(:singleton_name)
165165
instance_variable_set(ivar_name, association_model.find(:params => {:"#{self.class.element_name}_id" => self.id}))
166+
else
167+
instance_variable_set(ivar_name, association_model.find(:one, :from => "/#{self.class.collection_name}/#{self.id}/#{method_name}#{self.class.format_extension}"))
166168
end
167169
end
168170
end

test/cases/base_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1249,6 +1249,18 @@ def test_parse_resource_with_has_one_makes_get_request_on_child_route
12491249
assert product.inventory.status == ActiveSupport::JSON.decode(@inventory)['status']
12501250
end
12511251

1252+
def test_parse_non_singleton_resource_with_has_one_makes_get_request_on_child_route
1253+
accepts = { 'Accept' => 'application/json' }
1254+
ActiveResource::HttpMock.respond_to do |mock|
1255+
mock.get '/posts/1.json', accepts, @post
1256+
mock.get '/posts/1/author.json', accepts, @matz
1257+
end
1258+
1259+
Post.send(:has_one, :author, class_name: 'Person')
1260+
post = Post.find(1)
1261+
assert post.author.name == ActiveSupport::JSON.decode(@matz)['person']['name']
1262+
end
1263+
12521264
def test_with_custom_formatter
12531265
addresses = [{ :id => "1", :street => "1 Infinite Loop", :city => "Cupertino", :state => "CA" }].to_xml(:root => :addresses)
12541266

0 commit comments

Comments
 (0)