【问题标题】:Nested attributes not saving when updating object更新对象时不保存嵌套属性
【发布时间】: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


【解决方案1】:

好的,我发现了我遇到的问题。

我的课程实际上是这样布置的

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 Travel < ActiveRecord::Base
  attr_accessible :segments_attributes
   has_many :segments, :class_name => "TravelSegment", :dependent => :destroy, :foreign_key => "flight_travel_id"
  accepts_nested_attributes_for :segments, :allow_destroy => true
end

class FlightTravel < Travel
  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

我期待 FlightTravel 段覆盖 Travel 段,但由于某种原因它没有。它适用于创建记录,但不适用于您想要更新时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多