[英]:autosave ignored on has_many relation — what am I missing?
我有一對班級:
class Collection < ActiveRecord::Base
has_many :items, autosave: true
end
class Item < ActiveRecord::Base
belongs_to :collection
end
來自文檔 :
當:autosave為true時,無論是否為新記錄,都會保存所有子項:
但是當我更新一個Item
並保存其父Collection
, Item
的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, collection_id: 1, name: "item1", created_at: "2012-07-23 00:00:25", 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, name: string, created_at: datetime, updated_at: datetime), @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, collection_id: 1, name: "item1", created_at: "2012-07-23 00:00:25", updated_at: "2012-07-23 00:00:25">], @reflection=#<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, name: string, created_at: datetime, updated_at: datetime), @foreign_key="collection_id", @active_record_primary_key="id", @type=nil>, @owner=#<Collection id: 1, name: "collection", created_at: "2012-07-23 00:00:10", updated_at: "2012-07-23 00:00:10">, @updated=false, @loaded=true, @association_scope=[#<Item id: 1, collection_id: 1, name: "item1", created_at: "2012-07-23 00:00:25", updated_at: "2012-07-23 00:00:25">], @proxy=[#<Item id: 1, collection_id: 1, name: "item1", created_at: "2012-07-23 00:00:25", updated_at: "2012-07-23 00:00:25">], @stale_state=nil>
然后,我們可以找到通過此關聯關聯的實際對象:
> a.target
=> [#<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 = c.items.first
此行從數據庫中提取正確的項目,但不將其附加到集合c。 它是一個與物體不同的紅寶石物體
i = c.items[0]
如果您用第二行替換第一行,您的示例將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.