Two models accept nested attributes for each other, create stack level too high

I am wondering if I am only having this problem. To define this, I created two very simple models.

# user.rb class User < ActiveRecord::Base has_one :role, :inverse_of => :user accepts_nested_attributes_for :role end # role.rb class Role < ActiveRecord::Base belongs_to :user, :inverse_of => :role accepts_nested_attributes_for :user end 

In the rails console, an attempt to update a simple attribute of the Role class fails if the User model is loaded.

 Loading development environment (Rails 3.2.2) 1.9.3-p194 :001 > Role.first.update_attribute(:role_type, 72) => true 1.9.3-p194 :002 > Role.first.tap {|r| r.user}.update_attribute(:role_type, 72) SystemStackError: stack level too deep from /Users/enelson/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb/workspace.rb:80 Maybe IRB bug! 

If I remove one of the accepts_nested_attributes directives, this problem will disappear. I think the easy answer here is "OK, then why don't you get rid of one of them?" The problem is that you will need to rewrite many existing pages in the application, and if there is another fix or workaround, I would like to hear about it.

+4
source share
3 answers

Structurally, this is not the correct composition, in the role of which there is a "User". It might be better to fix the design at this point rather than leave it.

Both relationships are also defined as β€œinverse” to the other; which can also contribute to infinite recursion.

+3
source

I had the same problem: https://github.com/rails/rails/issues/7809 and then this pull request is https://github.com/rails/rails/pull/7824 . Added it as monkeypatch for the project, I hope that he will not present any unpleasant errors.

+1
source

According to the doc, you should remove accetps_nested_attributes_for from the Role model and save both inverse_of parameters.

0
source

Source: https://habr.com/ru/post/1480231/


All Articles