我有一对课程:
class Collection < ActiveRecord::Base has_many :items,autosave: true end class Item < ActiveRecord::Base belongs_to :collection end
从docs:
When :autosave is true all children is saved,no matter whether they are new records:
但是当我更新一个项目并保存其父集合时,该项目的upated属性不能被保存:
> c = Collection.first => #<Collection id: 1,name: "collection",created_at: "2012-07-23 00:00:10",updated_at: "2012-07-23 00:00:10"> > i = c.items.first => #<Item id: 1,collection_id: 1,name: "item1",created_at: "2012-07-23 00:00:25",updated_at: "2012-07-23 00:00:25"> > i.name = 'new name' => "new name" > c.save => true > Collection.first.items => [#<Item id: 1,updated_at: "2012-07-23 00:00:25">]
那么,我失踪了什么?
我使用的是Rails 3.2.5和Ruby 1.9.2.
所以我在ActiveRecord的源头做了一些挖掘.我们可以掌握c的自动保存协议:
> c.class.reflect_on_all_autosave_associations => [#<ActiveRecord::Reflection::AssociationReflection:0x007fece57b3bd8 @macro=:has_many,@name=:items,@options={:autosave=>true,:extend=>[]},@active_record=Collection(id: integer,name: string,created_at: datetime,updated_at: datetime),@plural_name="items",@collection=true,@class_name="Item",@klass=Item(id: integer,collection_id: integer,@foreign_key="collection_id",@active_record_primary_key="id",@type=nil>]
我认为这表明该协会是为了自动保存设立的.
然后我们可以得到对应于c的关联实例:
> a = c.send :association_instance_get,:items => #<ActiveRecord::Associations::HasManyAssociation:0x007fece738e920 @target=[#<Item id: 1,updated_at: "2012-07-23 00:00:25">],@reflection=#<ActiveRecord::Reflection::AssociationReflection:0x007fece57b3bd8 @macro=:has_many,@type=nil>,@owner=#<Collection id: 1,updated_at: "2012-07-23 00:00:10">,@updated=false,@loaded=true,@association_scope=[#<Item id: 1,@proxy=[#<Item id: 1,@stale_state=nil>
然后,我们可以找到通过此关联关联的实际对象:
> a.target => [#<Item id: 1,updated_at: "2012-07-23 00:00:25">]
这里找到的对象没有我之前提供的更新.