Skip to content

Commit 4fffccc

Browse files
Merge pull request #455 from seanpdoyle/has-many-where-chain
`has_many`: support chaining `where` clauses
2 parents d821ec5 + 61234e8 commit 4fffccc

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
read_attribute(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.where("#{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)