Skip to content

Commit f4ac23e

Browse files
guilleiguaranrafaelfranca
authored andcommitted
Merge pull request #97 from shamne/has_many
Avoid unnecessary external find to has_many association
1 parent 819e779 commit f4ac23e

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

lib/active_resource/associations.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,10 @@ def defines_has_many_finder_method(method_name, association_model)
144144
instance_variable_get(ivar_name)
145145
elsif attributes.include?(method_name)
146146
attributes[method_name]
147-
else
147+
elsif !new_record?
148148
instance_variable_set(ivar_name, association_model.find(:all, :params => {:"#{self.class.element_name}_id" => self.id}))
149+
else
150+
instance_variable_set(ivar_name, self.class.collection_parser.new)
149151
end
150152
end
151153
end

test/cases/association_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,12 @@ def test_has_many
3838
assert_equal 1, External::Person.reflections.select{|name, reflection| reflection.macro.eql?(:has_many)}.count
3939
end
4040

41+
def test_has_many_on_new_record
42+
Post.send(:has_many, :topics)
43+
Topic.stubs(:find).returns([:unexpected_response])
44+
assert_equal [], Post.new.topics.to_a
45+
end
46+
4147
def test_has_one
4248
External::Person.send(:has_one, :customer)
4349
assert_equal 1, External::Person.reflections.select{|name, reflection| reflection.macro.eql?(:has_one)}.count

0 commit comments

Comments
 (0)