Skip to content

Commit 3e9aae6

Browse files
committed
has_many: support chaining where clauses
Modify the `ActiveResource::Associations` module's `has_many` definition to invoke `Base.all`, rather than `Base.find(:all)` in order to utilize the deferred record fetching introduced in [#422][]. ```ruby class Person < ActiveResource::Base self.site = "https://example.com" has_many :people end person = Person.find(1) # => GET /people/1.json person.people # => GET /people.json?person_id=1 person.people.where(name: "Related") # => GET /people.json?person_id=1&name=Related ``` [#422]: #422
1 parent b7728b1 commit 3e9aae6

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

lib/active_resource/associations.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ def defines_has_many_finder_method(reflection)
148148
elsif attributes.include?(method_name)
149149
attributes[method_name]
150150
elsif !new_record?
151-
instance_variable_set(ivar_name, reflection.klass.find(:all, params: { "#{self.class.element_name}_id": self.id }))
151+
instance_variable_set(ivar_name, reflection.klass.all(params: { "#{self.class.element_name}_id": self.id }))
152152
else
153153
instance_variable_set(ivar_name, self.class.collection_parser.new)
154154
end

test/cases/association_test.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,24 @@ def test_association_class_build
3939
def test_has_many
4040
External::Person.send(:has_many, :people)
4141
assert_equal 1, External::Person.reflections.select { |name, reflection| reflection.macro.eql?(:has_many) }.count
42+
43+
ActiveResource::HttpMock.respond_to.get "/people.json?person_id=1", {}, { people: [{ id: 2, name: "Related" }] }.to_json
44+
person = External::Person.new({ id: 1 }, true)
45+
46+
people = person.people
47+
48+
assert_equal [ "Related" ], people.map(&:name)
49+
end
50+
51+
def test_has_many_chain
52+
External::Person.send(:has_many, :people)
53+
54+
ActiveResource::HttpMock.respond_to.get "/people.json?name=Related&person_id=1", {}, { people: [{ id: 2, name: "Related" }] }.to_json
55+
person = External::Person.new({ id: 1 }, true)
56+
57+
people = person.people.where(name: "Related")
58+
59+
assert_equal [ "Related" ], people.map(&:name)
4260
end
4361

4462
def test_has_many_on_new_record

0 commit comments

Comments
 (0)