Skip to content

Commit

Permalink
Validate loaded_#{association}? collecting @changed_attributes to avo…
Browse files Browse the repository at this point in the history
…id SystemStackError: stack level too deep for mutual delegation beetween models
  • Loading branch information
pahanix committed Jan 12, 2010
1 parent b63197e commit 03e0f11
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/delegates_attributes_to.rb
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,12 @@ module InstanceMethods
def changed_attributes_with_associations
result = {}
self.class.dirty_associations.each do |association, attributes|
association_changed_attributes = send(association).try(:changed_attributes) || {}
# If association isn't loaded yet it isn't changed at all. So we skip it.
# If we don't skip it and have mutual delegation beetween 2 models
# we get SystemStackError: stack level too deep while trying to load
# a chain like user.profile.user.profile.user.profile...
next unless send("loaded_#{association}?")
association_changed_attributes = send(association).send(:changed_attributes) || {}
result.merge! association_changed_attributes.slice(*attributes)
end
changed_attributes_without_associations.merge!(result)
Expand Down
28 changes: 28 additions & 0 deletions spec/model/mutual_delegation_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
require File.join(File.dirname(__FILE__), '..', 'spec_helper')

describe DelegatesAttributesTo, 'with mutual delegation' do

before :all do
UserNoDefault.has_one :profile, :foreign_key => 'user_id'
UserNoDefault.delegates_attributes_to :profile

Profile.belongs_to :user, :class_name => 'UserNoDefault', :foreign_key => 'user_id'
Profile.delegates_attributes_to :user
end

before :each do
@user = UserDefault.new
@user.about = "I'm Bob"
@user.profile.username = "bob"
@user.save!
end

describe "#save" do
it "should save and do not raise SystemStackError: stack level too deep" do
@user = UserDefault.find(@user.id)
@user.should_not be_changed
@user.profile.should_not be_changed
@user.save
end
end
end

0 comments on commit 03e0f11

Please sign in to comment.