简体   繁体   English

两个模型相互接受嵌套属性,生成堆栈级别太深

[英]Two models accept nested attributes for each other, generate stack level too deep

I'm wondering if I'm only the one with this issue. 我想知道我是否只是这个问题的那个人。 To pinpoint it, I have created two very basic 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, attempting to update a simple attribute of the Role class fails if the User model has been loaded . 在rails控制台中, 如果已加载User模型 ,则尝试更新Role类的简单属性将失败。

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 either one of the accepts_nested_attributes directives, this problem goes away. 如果我删除其中一个 accepts_nested_attributes指令,这个问题就会消失。 I guess the easy answer here is "well then, why don't you get rid of one of them?" 我想这里简单的答案是“那么,你为什么不摆脱其中一个呢?” The problem is that would involve rewriting a lot of existing pages in an application, and if there's a different fix or workaround, I'd like to hear about it. 问题是涉及重写应用程序中的大量现有页面,如果有不同的修复或解决方法,我想听听它。

Design-wise, it's not correct composition that Role "has a" User. 在设计方面,角色“拥有”用户是不正确的构成。 It may be better to correct the design at this stage, rather than leave it. 在这个阶段纠正设计可能更好,而不是留下它。

Both relationships are also defined as "inverse of" the other; 两种关系也被定义为另一种关系的“逆”; that might also possibly be contributing to the infinite recursion. 这也可能有助于无限递归。

I had the same issue, found this: https://github.com/rails/rails/issues/7809 and then this pull request https://github.com/rails/rails/pull/7824 . 我有同样的问题,发现这个: https//github.com/rails/rails/issues/7809然后这个拉取请求https://github.com/rails/rails/pull/7824 Added it as monkeypatch to project, hope it won't introduce any nasty bugs. 将它添加为项目的monkeypatch,希望它不会引入任何讨厌的错误。

根据文档 ,您应该从Role模型中删除accetps_nested_attributes_for ,并保留inverse_of

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM