Ruby on rails 3 为什么在RubyonRails中有很多关联会导致SystemStackError?
我无意中发现了SystemStackError,并在源代码中找到了它的起因。尽管如此,我还是不太明白为什么会这样。也许你能帮我 以下是场景:Ruby on rails 3 为什么在RubyonRails中有很多关联会导致SystemStackError?,ruby-on-rails-3,associations,Ruby On Rails 3,Associations,我无意中发现了SystemStackError,并在源代码中找到了它的起因。尽管如此,我还是不太明白为什么会这样。也许你能帮我 以下是场景: 有两种型号设施和位置,其型号定义如下所示 class Location < ActiveRecord::Base belongs_to :facility accepts_nested_attributes_for :facility end class Facility < ActiveRecord::Base has_many
有两种型号
设施
和位置
,其型号定义如下所示
class Location < ActiveRecord::Base
belongs_to :facility
accepts_nested_attributes_for :facility
end
class Facility < ActiveRecord::Base
has_many :locations
accepts_nested_attributes_for :locations
end
然后我想把两者联系起来
location.facility = facility
facility.locations << location
location.facility=facility
facility.locations我首先怀疑的是has\u many关联实际上是has\u太多了。换句话说,关系中的位置可能太多
事实上,考虑到您发布的代码,您似乎已经创建了一个无限的关联循环。你写道:
接受:设施的嵌套属性
我假设这会导致ActiveRecord打开facility属性,并在其中找到另一个具有另一个facility属性的位置。在深入挖掘之前,请尝试以下方法,看看是否有效:
facility.locations << location
location.facility = facility
facility.locations为什么两者都有
这一行:
facility.locations << location
通过这种方式,Rails负责设置facility\u id
字段,而不是在该字段之后进行手动赋值。我已经尝试了您后来的建议:“……或顺序,但顺序相反。”问题是,为什么它不以相反的方式工作。-尽管我在Rails控制台中,是否接受
的_嵌套的_属性_会导致问题?如果第二次设置facility属性,则在将位置添加到facility.locations属性时,没有循环引用可遵循。我认为你需要在这里重新考虑你的设计。将每个对象嵌套在另一个对象中是没有意义的。我不知道我可以用这种方式调用create
concatating。-我知道“位置的设施已经设置好了”,但为什么冗余是个问题呢?只要引用的对象不是零,它就可以工作。感叹号在这里不是强制性的。
facility.locations << location
facility.locations.create!(...)