我一直在努力解决一个问题,我正在更新一个具有两层嵌套字段的模型。
我有一个非常简单的模型
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 =&gt; {...})时,会使用正确的值正确更新对象。
我调用flight.save并且它没有做任何事情,并且由于某种原因只是跳过更新嵌套关联。我做错了什么?
答案 0 :(得分:0)
好的,我发现了我遇到的问题。
我的课程实际上是这样的
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细分,但由于某种原因,它没有。它适用于创建记录,但不适用于您想要更新的内容。