【发布时间】:2011-12-15 05:23:14
【问题描述】:
我一直在尝试解决一个问题,我在更新具有两层嵌套字段深度的模型时遇到了问题。
我有一个非常简单的模型
class Flight < Plan
attr_accessible :travels_attributes
has_many :travels, :class_name => "FlightTravel", :foreign_key => "plan_id", :dependent => :destroy
accepts_nested_attributes_for :travels, :allow_destroy => true
End
class FlightTravel < ActiveRecord::Base
attr_accessible :segments_attributes
has_many :segments, :class_name => "FlightSegment", :dependent => :destroy, :foreign_key => "flight_travel_id"
accepts_nested_attributes_for :segments, :allow_destroy => true
end
class FlightSegment < ActiveRecord::Base
end
现在,当我尝试在控制台中调用 flight.update_attributes(:travels_attributes => {...}) 时,将使用正确的值正确更新对象。
我调用了 flight.save 并且它没有做任何事情,并且由于某种原因只是跳过更新嵌套关联。我做错了什么?
【问题讨论】:
-
是否有任何可能失败的验证?它也将有助于查看失败的实际调用,也许使用简化的数据。您在控制台中对 update_attributes 的调用应保存到数据库中。我认为使用 :travel_attributes[sic] 作为键是一个错字。
-
是的,抱歉应该是 travels_attributes。已更新。不验证,因为它甚至没有命中 FlightSegment 类的 before_validation 回调
-
你能不能在 rails 控制台做这个,然后在#save 之后看看 flight.errors 是否为空?
-
p.errors #@messages=#
-
这就像活动记录正在跳过对嵌套对象的更新,因为它认为它还没有被更新。如果我对 Flight 对象进行更改,然后保存,它将更新它
标签: ruby-on-rails nested-attributes